Select one (this) item from <li> (jQuery/javascript)

167 views Asked by At

I have a <ul> list in my HTML, and inside each <li> within that, I have an element with the id vid.

With jQuery, I want to make it so that when I click the title of each <li>, the #vid element in that <li> (just the one that was clicked) will appear/disappear.

My code to toggle the #vid div works, but it affects all of the #vid elements, not just one.

HTML:

<ul class="list">
    <li>
      <h3 class="title">First Title</h3>
      <p class="tags">tags, tags, tags</p>
      <div id="vid">
  Now you see me!
</div>
    </li>
    <li>
      <h3 class="title">Second Title</h3>
      <p class="tags">etc, etc, etc</p>
      <div id="vid">
  Now you see me!
      </div>
    </li>
</ul>

jQuery:

var thisli = $('li', this);
  var thisvid = $('#vid', thisli);
  var clicks = 0;

  $('h3', this).click(function() {
    if(clicks % 2 === 0){
      $(thisvid, this).show();
      }else{
      $(thisvid, this).hide();
        }
    ++clicks;
});
  });
1

There are 1 answers

0
Rick Su On BEST ANSWER

#ID should be unique

so I use class="vid" in the code below.

jQuery(function($) {
  $("h3").click(function() {
    $(this).siblings(".vid").toggle();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list">
  <li>
    <h3 class="title">First Title</h3>
    <p class="tags">tags, tags, tags</p>
    <div class="vid">
      Now you see me!
    </div>
  </li>
  <li>
    <h3 class="title">Second Title</h3>
    <p class="tags">etc, etc, etc</p>
    <div class="vid">
      Now you see me!
    </div>
  </li>
</ul>