Javascript handling through a button multiple snippets of Html text

Asked

Viewed 19 times

-2

The code below works for a specific ID, I needed a code that affects several elements and not just a specific id.

function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

<button onclick="myFunction()">Click Me</button>

<div id="myDIV">
  This is my DIV element.
</div>
  • Please click [Edit] and put an example of HTML and what elements you want to modify at once. It has several ways to do, but it will depend on the structure of the page and what elements you want to take

  • Important you [Dit] your question and explain objectively and punctually the difficulty found, accompanied by a [mcve] of the problem and attempt to solve. To better enjoy the site, understand and avoid closures and negativities worth reading the Stack Overflow Survival Guide in English.

1 answer

0


This happens because in html the id is to give a indentifier for only 1 element, to select several of them, one of the ways is to use the atribitus class.

The code would look like this:

<head>
<script>
function myFunction() {
          var x = document.getElementsByClassName("myClass");
          for(var i = 0; i < x.length; i++){
              if (x[i].style.display === "none") {
                x[i].style.display = "block";
              } else {
                x[i].style.display = "none";
              }
            }
        } 
</script>    
</head>
<body>
        <button onclick="myFunction()">Click Me</button>
        
        <div class="myClass">
          This is my DIV element.
        </div>
        <div class="myClass">
          This is my other DIV element.
        </div>
        <div class="myClass">
          This is my new DIV element.
        </div>
</body>

  • 1

    "to select several of them, use the atríbuto class" - this implies that using classes is the only way, but it is not. For example, with querySelectorAll you can use several different criteria (by tag name, attribute name/value, even multiple id’s at once, or any combination of these, etc.). Anyway, without knowing the structure of HTML and what elements you want to pick up, any answer will be a guess (I asked the author of the question to clarify this information, because without it you can not suggest the best solution)

  • Thanks, I forgot the querySelectorAll, I just edited the answer.

  • I had forgotten to add a for, because the getElementsByClassName returns a array with the elements, test now to see if it works

  • Thank you so much! It worked now!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.