Basically I need a less stupid way to do this:
var x = getElementById('not-important');
x.parentElement.parentElement.parentElement.parentElement....parentElement.style.display = 'none';
In my case I have to use the .parentElement eight times. (FYI it's looking for the containing div
for a link/advert that directs our users to another website, on pages that we ingest from a 3rd-party organization.)
The element I need to hide is a div
and the only defining characteristic is it has a class name of "Enh". Other divs within the page have the class name and they cannot be deleted, thankfully though there's only one div
with class 'Enh' within the structure I'm trying to delete.
So, the whole structure is something like this:
<div class='Enh'>
<div>
<div>
...
<div id='not-important>
<a href='http://another.domain'>delete me<a>
</div>
...
</div>
</div>
</div>
<div class='Enh'>
I must not be deleted
</div>
And like I said, the structure that needs to be deleted is coming from outside my control and could change at anytime, and if they change it from 8 nested divs to 7-or-less nested divs then my dumb code from above could accidently delete the whole page or section.
Anyone want to take a stab at this?
You can use the closest method from Element interface for this
As per the MDN definition:
The closest() method of the Element interface traverses the element and its parents (heading toward the document root) until it finds a node that matches the specified CSS selector.
const el = document.getElementById('not-important');
const containerToRemove = el.closest('.Enh');
if (containerToRemove) {
containerToRemove.style.display = 'none';
}