Cameron
Cameron

Reputation: 28803

jQuery if an element has two parent uls

How would I detect if an element had two parent uls so for example:

<ul>
   <li>Link
      <ul>
        <li>Link
            <ul>
                <li class="this">Link</li>
            </ul>
        </li>
      </ul>
   </li>
</ul>

I've tried:

if ($('.this').parent('ul').parent('ul') == true)

but it doesn't seem to work... Can anyone help? Thanks

Upvotes: 2

Views: 534

Answers (6)

Arun Kumar
Arun Kumar

Reputation: 61

Try below code snippet:

var ullength = $('.this').parents('ul').length; if (ullength == 3) { //your code }

For live demo http://jsfiddle.net/creativegala/rMk9b/2/

Upvotes: 0

Arindam
Arindam

Reputation: 998

There are 2 ways of doing this.

1) bottom up - starting from the element.

if($('.this').parents('ul').length >=2) { // >= to accomodate your markup
    return true;
}

2) top-down

if($('ul ul li.this').length > 0) {
    return true;
} // this is a better solution as it will return true for your markup as well, which has 3 ul's before the desired li

Performance wise, you should choose the first method, as it does not check every ul sub-tree, but only checks to see if the '.this' element has 2 or more parent ul's.

Upvotes: 2

Andy Rose
Andy Rose

Reputation: 16984

The reason your code does not work is the first parent ul's immediate parent is an li, you would have to do this:

if ($('.this').parent('ul').parent('li').parent('ul') == true)

The jQuery parents() function accepts a selector so you could do this so assert there are two parent ul's:

if($('.this').parents('ul').length == 2) { ... }

or if you want to assert at least 2 parent ul's:

if($('.this').parents('ul').length >= 2) { ... }

Upvotes: 4

4b0
4b0

Reputation: 22323

try:

if ($('.this').parent('ul').parent('ul').length > 0)
{
  //your code
}

Upvotes: 0

Bartosz
Bartosz

Reputation: 3358

Use parents() which differs from parent() that it traverse up many levels.

$('.this').parents('ul').length

http://api.jquery.com/parents/

Upvotes: 1

Grim...
Grim...

Reputation: 16953

if ($('.this').parents('ul').length == 2)

In the code you posted above it actually has three, so I suspect you want > 1 rather than == 2.

Upvotes: 1

Related Questions