gpt4 book ai didi

javascript - JS - 删除段落中的所有图像和格式

转载 作者:行者123 更新时间:2023-12-03 09:33:08 24 4
gpt4 key购买 nike

我想从 div 节点中删除所有子级,并且对于删除的每个段落子级,我想将它们添加到新的段落元素中,以便所有段落合并为一个,并删除其他任何内容。

但是,在删除所有段落并将它们添加到这个新段落时,我还想删除所有图像(而不仅仅是删除开始和结束箭头)并确保所有单词的格式保持相同(只是11pt 标准字体)。

我希望这是有道理的。这是我到目前为止所拥有的:

var newP = document.createElement('P');
var paras = comment.getElementsByTagName('P');
var counter = 0;
while (paras[0]) {
var next = paras[0]; // needs to be 0;
if (next.innerHTML.length > 8) { // to safely ignore  
counter++;
if (counter < 3)
newP.innerHTML += next.innerHTML + "<br /><br />";
}

comment.removeChild(next); // comment is the div which holds the new para
next = paras[0];

if (!next)
newP.innerHTML += "<a href='" + link + "'>click to view full entry</a>";
}
comment.appendChild(newP);

以下是需要格式化的 HTML 标记示例:

<div class="comment">
<h3>Heading</h3>
<p style="font-weight: bold">This has been formatted which should be removed. <span style="font-size: 14pt; color: red;"> This also includes all span tags!</span></p>
<p>This is a para <a href="">with an anchro</a></p>
<div> this is a div with an image <img src="//placehold.it/64X64" /></div>
<p>This is an image in the middle of a paragraph <img src="http://www.thinkstockphotos.com.au/CMS/StaticContent/Hero/TS_AnonHP_462882495_01.jpg"/> which I want to remove, and not just the arrows</p>
</div>

我希望它看起来像这样:

<div class="comment">
<p>Heading</p>
<p>This has been formatted which should be removed. This also includes all span tags!</p>
<p>This is a para with an anchro</p>
<div> this is a div with an image</div>
<p>This is an image in the middle of a paragraph which I want to remove, and not just the arrows</p>
</div>

编辑:这不是重复的,因为我想完全删除所有图像以及图像开始和结束标记之间的所有属性/文本(不仅仅是删除构成标记的箭头)并删除所有格式!

最佳答案

alert(document.body.outerHTML);

var imgs = Array.prototype.slice.call(document.querySelectorAll("img"));

for (var q=0; q<imgs.length; ++q) {
imgs[q].parentNode.removeChild(imgs[q]);
}

var ps = Array.prototype.slice.call(document.querySelectorAll("p"));

for (var q=0; q<ps.length; ++q) {
var p = ps[q];
p.textContent = p.textContent;
p.setAttribute("style", "");
}

alert(document.body.outerHTML);
<div class="comment">
<h3>Heading</h3>
<p style="font-weight: bold">This has been formatted which should be removed. <span style="font-size: 14pt; color: red;"> This also includes all span tags!</span></p>
<p>This is a para <a href="">with an anchro</a></p>
<div> this is a div with an image <img src="//placehold.it/64X64" /></div>
<p>This is an image in the middle of a paragraph <img src="http://www.thinkstockphotos.com.au/CMS/StaticContent/Hero/TS_AnonHP_462882495_01.jpg"/> which I want to remove, and not just the arrows</p>
</div>

关于javascript - JS - 删除段落中的所有图像和格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31432420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com