-1

I have a few div and i want to hide them with js. But my script just hides one of them. How can I hide all of them?

function hide(id) {
  document.getElementById(id).style.display = "none";
}

hide("test");
<div id="test" data-studio="disney" data-month="mar" data-action="action" data-serie="serie" data-platform="disney+"  class="product">Dinner</div>
          <div id="test" data-category="first meal" class="product">First meal</div>
          <div id="test" data-category="garnish" class="product">Garnish</div>

And how can I just hide elements with the data-category garnish?

  • Id's are meant to be unique, try assigning `class` names instead - [some examples](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll). – Emissary Apr 06 '21 at 16:17
  • Using a simile, it's like pretending to send a text message to all phones with the same number ;-) – Álvaro González Apr 06 '21 at 16:27

2 Answers2

1

getElementById select just THE element with the corresponding attribute id. If there are several with the same id, it will still return just one.

What you need to do is use the class attribute like that :

function hide(class) {
  var thingsToHide = document.getElementsByClassName(class); //Get all products class elements
   for (var i=0; i<thingsToHide.length; i++) {
      thingsToHide.item(i).style.display = "none";
   }
}

hide("product");

and the html :

<div id="test" data-studio="disney" data-month="mar" data-action="action" data-serie="serie" data-platform="disney+"  class="product">Dinner</div>
          <div id="test" data-category="first meal" class="product">First meal</div>
          <div id="test" data-category="garnish" class="product">Garnish</div>
Axel W
  • 63
  • 7
0

IDs are meant to be unique. That's why getElementById returns 1 result, and not an array of results. It's giving you the first match.

Instead, use a class, like this:

<div class="hide-me">Hello</div>

Then in the script:

document.querySelectorAll('.hide-me').forEach(it => hide(it))

The querySelectorAll function does return an array of matches, searching using CSS selector syntax.

salezica
  • 74,081
  • 25
  • 105
  • 166