开发者

Jquery check if parent has an ID

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开发者_Python百科 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?


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.


$('li').each(function() {
    if ($(this).parent('#selected').length) {
    ⋮
    } else {
    ⋮
    }
});

works great for me.


Not positive, but I think it should just be

if ($('li').parents('#selected')) {...} else {...}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜