Alexander Orbes Alexander Orbes - 2 months ago 8
jQuery Question

How I Can Get the Id of a li cicked

I have a tree generated from database in apex 4.2:



<ul id="ltr">
<li id="00010" class="open"><a href="" style="" class=""><ins>&nbsp;</ins>Root</a>
<ul><li id="00110" class="open"><a href="" style="" class=""><ins>&nbsp;</ins>CHILD</a>
<ul><li id="00563" class="open"><a href="" style="" class=""><ins>&nbsp;</ins>CHILD</a>
<ul><li id="02057" class="leaf"><a href="" style="" class=""><ins>&nbsp;</ins>LAST CHILD</a></li>
</ul></li></ul>
</li>
</ul>
</li>
</ul>





I use a click function to select the id of a node, with class leaf no problem, but with open class selects the parent and the parent id, How Can I select the id of the node clicked ?

$(".leaf").click(function(){
alert($(this).attr('id'));
});


$(".open").click(function(){
alert($(this).attr('id'));
});

Answer

You need to use stopPropagation(), otherwise your event listener will execute for all three nested elements when clicking the inner element. And you shouldn't use numbers as an ID.

Heres a working Fiddle:

$(document).ready(function(){
  $(".open").click(function(e){
  		e.stopPropagation();
      alert($(this).attr("id"));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul id="ltr">
  <li id="a00010" class="open">
    <a href="" style="" class=""><ins>&nbsp;</ins>Root</a>
      <ul>
        <li id="a00110" class="open"><a href="#"><ins>&nbsp</ins>CHILD</a>
          <ul>
            <li id="a00563" class="open"><a href="#"><ins>&nbsp;</ins>CHILD</a>
              <ul>
                <li id="a02057" class="leaf"><a href="#"><ins>&nbsp;</ins>LAST CHILD</a></li>
              </ul>
            </li>
          </ul>
        </li>
      </ul>
  </li>
</ul>

EDIT: If you want to select .open and .leaf just change the selector to:

$(".leaf, .open")