'Javascript how to append all class list to innerHTML then apply it on the webpage
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
Solution 1:[1]
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 class="keep">keep this</div>
<div>don't care about this</div>
<div>don't care about this</div>
<div class="keep">keep this too</div>
<div>don't care about this</div>
<div class="keep">keep this also</div>
you can change .keep
with whatever class you want.
Solution 2:[2]
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 class="HoXoMd D1wxyf G4EHhc">Remains 1</p>
<p class="HoXoMd D1wxyf G4EHhc">Remains 2</p>
<p class="HoXoMd D1wxyf G4EHhc">Remains 3</p>
<p class="HoXoMd">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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sadra M. |
Solution 2 | Teemu |