Dynamic way to hide divs vanilla javascript

Tags: , , , ,



Is there a more dynamic way to hide/show divs that are identical in structure with no identifiers? Click to show I’m some stuff

<div class="setup" onclick="show(1)">
Click to show
  <p class="hidden">
    I'm more stuff
  </p>
</div>


function show(elem) {   
  var p = document.getElementsByClassName("hidden");
  if (p[elem] != undefined) {
    if (p[elem].style.display == "none") {
        p[elem].style.display = "block";
    } else {
      p[elem].style.display = "none";
    }
  }
}

http://jsfiddle.net/ba7yfmz6/29/

Answer

Use this:

<div class="setup" onclick="show(this)">

JavaScript:

function show(elem) {
    var paragraph = elem.querySelector(".hidden");
    if (paragraph.style.display == "none") {
        paragraph.style.display = "block";
    } else {
        paragraph.style.display = "none";
}

Hopefully this helps!



Source: stackoverflow