Skip to content
Advertisement

Dynamic way to hide divs vanilla javascript

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/

Advertisement

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!

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement