How can I use getElementsByClassName(<classname>).outerHTML="" to hide a <div> when there are multiple names for the div's class?

Viewed 66

I am trying to learn how to hide <div> sections on a webpage, using javascript getElementsByClassName("<classname>").outerHTML="".

It all works great if the element I am hiding e.g. <div class="someclassname">Some content I want to hide</div>. Or, I have success if using getElementByID("<divId>") if working with e.g. <div id="somedivID">.

The problem is, when wanting to hide a <div> that has no id and when there are multiple names listed for the div's class such as below:

<div class="cake forest carousel">Some content I want to hide.</div>

How can I hide such a div that has not id and no single class name?

1 Answers

For classes, you can use document.querySelectorAll() along with css selectors, like this:

document.querySelector('button').addEventListener('click', () => {
  document.querySelectorAll('.cake')[0].style.display = 'none';
});
<div class="cake forest carousel">Some content I want to hide.</div>
<button>Hide content</button>

With classNames, remember that you can specify ALL the classNames (sometimes that is useful to pinpoint one element if there are other elements that contain part of the classList:

document.querySelectorAll('.cake.forest.carousel')[0] . . .

Also note that document.querySelectorAll() returns a collection, not a string - which is why it is necessary to use the [0] notation to choose the first element returned in the collection.

Using getElementsByClassName() is much the same idea - again, it returns a collection and one must either use the [0] notation to get the first element (usually if only one is returned), or a forEach() loop to choose the desired element based on other criteria.

document.querySelector('button').addEventListener('click', () => {
  document.getElementsByClassName('cake forest')[0].style.display = 'none';
});
<div class="cake forest carousel">This div has classes cake, forest and carousel</div>
<div class="cake">This div only has class cake</div>
<button>Hide divs with classes cake AND forest</button>

Related