1

Currently the page only works for the first list item. I want the onclick show/hide to work for all list elements. I tried changing it to get element by class, yag name, but couldn't get it right.

Here is the code:

HTML

<ul>

  <li id="virsraksts" class="slid">
    <h3>{{ post.date | date: "%B %d, %Y" }}: {{ post.title }}</h3>
  </li>
  <div id="kontents" class="storijs">
    <div style="height:20px;"></div>
    {{ post.content }}
    <div style="height:20px;"></div>
  </div>

  <li id="virsraksts" class="slid">
    <h3>{{ post.date | date: "%B %d, %Y" }}: {{ post.title }}</h3>
  </li>
  <div id="kontents" class="storijs">
    <div style="height:20px;"></div>
    {{ post.content }}
    <div style="height:20px;"></div>
  </div>

  <li id="virsraksts" class="slid">
    <h3>{{ post.date | date: "%B %d, %Y" }}: {{ post.title }}</h3>
  </li>
  <div id="kontents" class="storijs">
    <div style="height:20px;"></div>
    {{ post.content }}
    <div style="height:20px;"></div>
  </div>
</ul>

CSS

.storijs {
    display: none;
}

.para {
    display: block;
}

JS

document.getElementById("virsraksts").onclick = function() {
  myFunction()
};

function myFunction() {
  document.getElementById("kontents").classList.toggle("para");
}
Nico
  • 12,493
  • 5
  • 42
  • 62
PaulThunder
  • 13
  • 1
  • 6
  • Give them all same class name and use loop over HTMLCollection to attach event to all of them. Also check http://stackoverflow.com/questions/21700364/javascript-adding-click-event-listener-to-class/21700383#21700383 – dfsq Jan 11 '17 at 22:51

1 Answers1

1

You have a few options by either using tag name or class. I have created a simple JSFiddle to achieve this.

Basically you can capture all the li elements using

var elements = document.getElementsByTagName('li')

This will return an array of all the li elements. Next you iterate this array binding your click handler.

var elements = document.getElementsByTagName('li')
for(var i=0;i<elements.length;i++)
    elements[i].onclick = myFunction;

This will now fire the myFunction on click of each li element in the array. Finally your function (handler) can use the this keyword to toggle the class as:

var elements = document.getElementsByTagName('li')
for (var i = 0; i < elements.length; i++)
  elements[i].onclick = myFunction;

function myFunction(e) {
  this.classList.toggle('para');
}
Nico
  • 12,493
  • 5
  • 42
  • 62
  • Hello, Im trying out this solution, while it now works for all list items, it doesn't apply the display: block; for all the divs under the list items. – PaulThunder Jan 12 '17 at 07:31
  • as far as I understand, this.classList.toggle affects the
  • , however, the element with the toggling is the child
  • – PaulThunder Jan 12 '17 at 07:33