0

I have an html list with the following structure:

<ul id="dunderList">
  <li>Characters</li>
<div>
   <li>scott</li>
   <li>halpert</li>
   <li>beasley</li>
   <li>schrute</li>
</div>
</ul>

I want to toggle the div on click of the first ul with the id 'dunderList' but limit it to only click of that element. Right now with my jquery code even if I click the child list the div toggles.

js:

$(document).on('tap', '#dunderList', function() {

    $(this).find('div').toggle();
});

So, if I click on 'scott' the list shouldn't toggle but right now it does.

jsfiddle

bos570
  • 1,505
  • 2
  • 23
  • 45
  • Check [this Demo](http://jsfiddle.net/tusharj/95hk2hjz/7/) – Tushar Aug 06 '15 at 03:41
  • 1
    div is not a valid child of ul, also are you saying you have multiple elements with the id dunderList? id must be unique, if you need to have multiple elements, you need to use class instead – trex005 Aug 06 '15 at 03:43

2 Answers2

3

Your html is not valid as ul can have only li as its child.

You can have the click handler to target only the first li element, then toggle all its sibling elements like

//event name is changed to click to simulate the functioning here... change it to tap in your case
$(document).on('click', '#dunderList > li:first-child', function() {
  $(this).siblings().toggle();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="dunderList">
  <li>Characters</li>
  <li>scott</li>
  <li>halpert</li>
  <li>beasley</li>
  <li>schrute</li>
</ul>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Hi Arun!! was that event `tap` or `click`? cs when I ran your snippet it wasn't running! So just edited and made it to click! – Guruprasad J Rao Aug 06 '15 at 03:44
  • Oh Ok. Looks fine then.. :) You can revert it back buddy.. :) – Guruprasad J Rao Aug 06 '15 at 03:48
  • Thanks for the response...I am new to jquery what does '>' do in '#dunderList > li:first-child' – bos570 Aug 06 '15 at 03:48
  • @bos570 that is the child selector... not really required... you can just say `#dunderList li:first-child` with the above given markup – Arun P Johny Aug 06 '15 at 03:50
  • `>` is the [child combinator](http://stackoverflow.com/questions/3225891/what-does-the-greater-than-sign-css-selector-mean#3225905), or direct descendant combinator. It makes sure you are only matching the `li`s that are directly descendant of `#dunderList`, not from any nested `ul` you might have in the future. – Marcos Dimitrio Aug 06 '15 at 03:58
0

change your click handler to fire on the first list element, then find the div and toggle it:

$(document).on('tap', '#dunderList > li:first-child', function(e) {
    $(this).siblings('div').toggle();
})

http://jsfiddle.net/95hk2hjz/8/

swatkins
  • 13,530
  • 4
  • 46
  • 78