删除所有标签并创建一个包装内部html javascript的新元素

时间:2019-06-06 10:57:29

标签: javascript wrapper replacewith

我对javascript完全陌生,我不知道哪种方法是解决一个非常简单的问题的最佳方法。

我必须删除html页面的所有<p>标签并放入所有内容 在唯一的<p>标签中。

哪个可能是最干净的解决方案?

文字:

<p> text1 </p>
<p> text2 </p>
....
<p> text n </p>

预期结果:

<p>
text1,text2 ... text n
</p>

我从这个开始,但是我不知道该怎么做:

var p = document.getElementsByTagName('body')[0]
                .getElementsByTagName('p'); //get all the p inside body 
var i;

2 个答案:

答案 0 :(得分:1)

从所有Author.joins(:articles).merge(Articles.published).find(params[:author_id]) 中提取textContent,从文档中删除所有现有的p,然后创建一个新的p,其p是其他”,如果需要,可以使用分隔符将其加入:

textContent
const ps = [...document.querySelectorAll('p')];
const newText = ps
  .map(({ textContent }) => textContent)
  .join(',');
ps.forEach(p => p.remove());
document.body.appendChild(document.createElement('p')).textContent = newText;

答案 1 :(得分:0)

您可以使用以下类似的代码来满足您的要求。

org_html = document.getElementById("slidesContainer").innerHTML;
new_html = "<div id='slidesInner'>" + org_html + "</div>";
document.getElementById("slidesContainer").innerHTML = new_html;