Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery check if parent has an ID

Tags:

jquery

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?

like image 572
Alex Sleiborg Avatar asked Aug 23 '10 12:08

Alex Sleiborg


People also ask

How check ID exists or not in jQuery?

In jQuery, you can use the . length property to check if an element exists. if the element exists, the length property will return the total number of the matched elements. To check if an element which has an id of “div1” exists.

How do you know if an element has an ID?

Use the querySelector() method to check if an element has a child with a specific id, e.g. if (box. querySelector('#child-3') !== null) {} . The querySelector method returns the first element that matches the provided selector or null of no element matches.

How do I find a specific parent in jQuery?

jQuery | parent() & parents() with ExamplesThe parent() is an inbuilt method in jQuery which is used to find the parent element related to the selected element. This parent() method in jQuery traverse a single level up the selected element and return that element.


2 Answers

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.

like image 98
user113716 Avatar answered Oct 22 '22 05:10

user113716


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

works great for me.

like image 24
fragmentedreality Avatar answered Oct 22 '22 03:10

fragmentedreality