Home > Mobile >  Javascript how to append all class list to innerHTML then apply it on the webpage
Javascript how to append all class list to innerHTML then apply it on the webpage

Time:04-02

I want to remove all the elements in the page except for the elements that I want. I am using chrome inspect element console.

So I am thinking of this method:

document.body.innerHTML = texts.innerHTML;

I tried the code below but it only appends the 1st element of texts to body.innerHTML.

var texts = document.getElementsByClassName('HoXoMd D1wxyf G4EHhc');
for(let text of texts){
    document.body.innerHTML = text.innerHTML;
}

I tried the code below, it does appends but did not change the website, it only appends on the console when u print it:

var texts = document.getElementsByClassName('HoXoMd D1wxyf G4EHhc');
for(let text of texts){
    document.body.innerHTML  = text.innerHTML;
}

i am new to javascript thanks

CodePudding user response:

innerHTML is rarely a good tool for modifying existing document. Also modifying document during iterating a live collection may produce unexpected results.

You can collect all the elements except the wanted, and then remove them from the document, like this:

const texts = document.body.querySelectorAll('*:not(.HoXoMd.D1wxyf.G4EHhc)');
for (let text of texts) {
  text.remove();
}
<p>Paragraph 1</p>
<p >Remains 1</p>
<p >Remains 2</p>
<p >Remains 3</p>
<p >Paragraph 2</p>

The universal * selector collects all the elements in document.body, :not pseudo-class excludes the elements matching the selector passed to :not. The NodeList element.querySelectorAll returns is static, and you can remove elements in a loop without getting a mess a live list would cause.

It's notable, that using element.querySelectorAll is crucial, if you used document.querySelectorAll, all the elements in the document would be removed, including head and body, and nothing would be left on the page.

CodePudding user response:

You second code snippet is fine, you are just missing one thing: you have to clear all the html after selecting the elements you want to keep, and then start adding them again to your DOM.

// use querySelectorAll instead
var texts = document.querySelectorAll('.keep'); 

// clear all html
document.body.innerHTML = ''; // <- 

// add all the html you want back to the dom
for (const text of texts) 
  document.body.appendChild(text)
<div >keep this</div>
<div>don't care about this</div>
<div>don't care about this</div>
<div >keep this too</div>
<div>don't care about this</div>
<div >keep this also</div>

you can change .keep with whatever class you want.

  • Related