How to prevent jQuery event from bubbles to parent elements?

I have a series of nested ULs that look like this:

<ul class="categorySelect" id="">
  <li class="selected">Root<span class='catID'>1</span>
    <ul class="" id="">
      <li>First Cat<span class='catID'>2</span>
        <ul class="" id="">
          <li>cat in First<span class='catID'>3</span>
            <ul class="" id="">
            </ul>
          </li>
          <li>another cat in first<span class='catID'>4</span>
            <ul class="" id="">
            </ul>
          </li>
        </ul>
      </li>
      <li>cat in root<span class='catID'>5</span>
        <ul class="" id="">
        </ul>
      </li>
    </ul>
  </li>
</ul>

Then I have jQuery that I intended to move the class "selected"to different LIs on click():

$(document).ready(function () {

    $("ul.categorySelect li").click(function () {
        $("ul.categorySelect li.selected").removeClass("selected");
        $(this).addClass("selected");
    })

});

When I tested this, at first it didn't work at all. I added a alert("click")click event inside the function, and I was able to say that it works, but the click event registered for both the child LIs and the parent LIs, which means that ultimately the root LI will always be selected as. / p>

Is there a way to prevent the event from executing click()in the parent LI?

+5
source share

All Articles