Search code examples
jquerydescendant

Using jQuery determine if element has a particular descendent element


I want to determine if the "li" clicked on has/contains a "ul" below it.

<ul id="menu">
  <li>Item One</li>
  <li>Item Two
    <ul>
      <li>Sub One</li>
      <li>Sub Two B</li>
    </ul>
  </li>
  <li>Item Three</li>
</ul>

My many tries always returns true because my methods seen to take into account everything, including "this":

$('ul#menu li').click(function() {
  if ($(this).has('ul')) {
    ...do something...;
  }
  return false;
});

Or

$('ul#menu li').click(function() {
  if ($(this).find('ul')) {
    ...do something...;
  }
  return false;
});

Or one more try:

$('ul#menu li').click(function() {
    if ($(this).filter(function( index ) {
        return $( "ul", this ).length >= 1;
        }) ) {
        ...do something...
    }
    return false;
});

I ended up cobbling this together, that works, but not elegant:

$('ul#menu li').click(function() {
    var offspring = $(this).children().toArray();
    if (offspring.length == 3) {  //ul in object adds 2 to length
       ...do something... 
    }
    return false;
});

This seems like a no brainer, but I must be missing something fundamental.

Thoughts?


Solution

  • .has() returns a jquery object, so will always return true. Seems like you need to check if it has any matched elements with .length:

    $('ul#menu li').click(function() {
      if ($(this).has('ul').length) {
        ...do something...;
      }
      return false;
    });