Shipwreck Shipwreck - 6 months ago 10
HTML Question

Hide/Show specific divs with JavaScript

I want to make an HTML element reference like this

<html> X
- description -

<head> X
- description -

<body> X
- description -


The description of the element is hidden by default so when I click on the "X" or the DIV that contains that element description, the description shows up or hide when I click it again.

This is my HTML code:

<h1>HTML Reference</h1>
<div id="reference-list">
<div class="list-element">&lt;html&gt;</div>
<div class="element-desc">Here's go description</div>
<div class="list-element">&lt;head&gt;</div>
<div class="element-desc">Here's go description</div>
</div>


I tried with jQuery but I dont know how to select the specific div containing the description of that element, since all the divs have the same class (otherwise I will have to create 100 class for each HTML element).

What I tried is this:

<script>
$(document).ready(function(){
$(".list-element").click(function(){
$(".element-desc").toggle();
});
});
</script>


This doesn't work since it show/hide the description of all the elements on the site.

Answer

You can use .next() if thats is the correct position of your element.

$(document).ready(function(){
    $(".list-element").click(function(){
        $(this).next().toggle();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1>HTML Reference</h1>
  <div id="reference-list">
      <div class="list-element">&lt;html&gt;</div>
      <div class="element-desc">Here's go description</div>
      <div class="list-element">&lt;head&gt;</div>
      <div class="element-desc">Here's go description</div>
  </div>