删除<a> tags with ES6 Javascript?

时间:2017-07-14 23:17:21

标签: javascript html

I desire removing all html tags in a the #bodyContent div id of a page, besides <a> tags, with ES6 Javascript (no jQuery).

The page is a quite long Wikipedia article that shows large amount of text of p, span, as well as img, among others.

Inside the p and span, there are many a tags. Actually, about 99.9% of the p tags include at least 1 a tag.

Removing all p tags that doesn't have an a inside them with the following code is ineffective because only about 0.1% of the text is removed:

for (const text of document.querySelectorAll("p")) {
    if (!text.querySelector("a")) {
        text.style.display = "none";
    }
}

I need a solution that will erase everything in the #bodyContent div of the page, which isn't a tags.

The end product should be a Wiki webpage filled only with a links.

2 个答案:

答案 0 :(得分:0)

您只需从a元素中选择所有p元素,然后仅使用a元素替换内容。类似的东西:

const content = document.querySelector('#bodyContent');
let links = content.querySelectorAll('a');
content.innerHtml = '';
links.foreach(a => {
    content.appendChild(a);
});

答案 1 :(得分:-1)

只需删除所有内容,然后将链接放回:

const el = document.querySelector("div#bodyContent");
const links = el.querySelectorAll("a");
while (el.hasChildNodes())
    el.removeChild(el.firstChild);
for (const link of links)
    el.appendChild(link);