0

In CSS I am trying to assign multiple elements ids to a class and change their display property to "none" using a javascript with both document.getElementsByClassName and style.display. In css I used #content.myClass which I found in this article.

I am doing this to reduce the unique selectors and keep my code efficient.

html:

  <p id="toy-pictures-latest" class="panel">Latest Toy Pictures</p><br>
         <p id="toy-pictures-greatest" class="panel">Greatest Toy Pictures</p>

css:

#toy-pictures-latest.panel{
    display: inline;
}

#toy-pictures-greatest.panel{
        display: inline;
}

js:

document.getElementsByClassName('panel').style.display = "none";

codepen

It doesn't appear to be making the text vanish as expected. How should I approach this? No jQuery, please.

caston
  • 159
  • 12
  • 2
    `getElementsByClassName` returns a collection, not a single element. If you want the first one use `getElementsByClassName('panel')[0]` or `document.querySelector('.panel')` – charlietfl Sep 13 '20 at 00:28
  • document.querySelector('.panel').style.display = "none"; makes the first line vanish but not the second. [codepen](https://codepen.io/j354374/pen/yLOjwwx) – caston Sep 13 '20 at 00:49
  • 1
    Then you need to loop over the collection and modify each instance you want. querySelector only finds first match in page – charlietfl Sep 13 '20 at 00:50
  • var panels = document.querySelectorAll('.panel'), i; for (i = 0; i < panels.length; ++i) { panels[i].style.display = "none"; } – caston Sep 13 '20 at 01:53

0 Answers0