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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With