tags:

views:

40

answers:

2

Hi i'm trying to check if a parent element contains an ID

Here is my list

<ul>
<li></li>
<li id="selected">
    <ul>
        <li></li>
        <li></li>
    </ul>
</li>
<li></li>
</ul>

Don't know how to make a correct list in here?

if (jQuery(LiElement).parent("#selected"))
{
    //If parent has id=selected
}
else
{
    //If parent dont have id=selected
}

Can someone help me please?

A: 

Not positive, but I think it should just be

if ($('li').parents('#selected')) {...} else {...}
Squirkle
You need to test .length; .parents() will always return a jQuery object (even if nothing matches) which will evaluate to true
Bobby Jack
+3  A: 

You could test the length property of the .parent("#selected"):

if( Query(LiElement).parent("#selected").length ) 

If the parent has the #selected ID, it will return 1 (true), otherwise 0 (false).

Note that you are testing the immediate parent only. I think this is what you wanted.

If the ID is not the immediate parent, you could use closest() to test any ancestor for the ID.

if( Query(LiElement).closest("#selected").length ) 

Just be aware that this will also test the current element.

patrick dw
+1 for .closest(), probably what is needed, but poster will have to decide.
Mark Schultheiss