xion
xion

Reputation: 93

List Open by OnClick

I have a multi-level list. Only the first level of the list is visible. Now I want to click on an element in the list and the subitems will appear.

How is that possible with js??

<!DOCTYPE html>
<html>
<body>

<h2>A Nested List</h2>
<div id="mylist">
<ul>
  <li>Coffee</li>
  <li>Tea
    <ul>
    <li>Black tea</li>
    <li>Green tea</li>
    </ul>
  </li>
  <li>Milk</li>
</ul>
</div>
</body>
</html>

Upvotes: 0

Views: 4229

Answers (1)

zork media
zork media

Reputation: 972

Yes, you can:

// JavaScript
jQuery( "li:has(ul)" ).click(function(){ // When a li that has a ul is clicked ...
	jQuery(this).toggleClass('active'); // then toggle (add/remove) the class 'active' on it. 
});
/* CSS */
ul li ul {
  display: none; /* Hide the nested list first */
}
ul li.active ul {
  display: block; /* Show the list when class 'active' is added to the li */ 
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>A Nested List</h2>
<div id="mylist">
<ul>
  <li>Coffee</li>
  <li>Tea
    <ul>
    <li>Black tea</li>
    <li>Green tea</li>
    </ul>
  </li>
  <li>Milk</li>
</ul>
</div>

Upvotes: 1

Related Questions