Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If element does not have parent with specific class

I am trying to create an if statement in jQuery for elements that have a parent with a specific class.

This is what I've come up with so far but it's not right.

if(!$(".myElem").parents(".myDiv")) {
    console.log("test")
};

Can anyone point me in the right direction please.

like image 741
Tom Avatar asked Mar 28 '13 11:03

Tom


People also ask

How do you know if a parent element has a class?

Use the parentElement property to select the parent of the element. Use the classList. contains() method to check if the parent contains the class. The method returns true if the element's class list contains the class and false otherwise.

Is there a CSS parent selector?

Let's be clear here, just in case someone is finding this from a search engine: there are no parent selectors in CSS, not even in CSS3.

What is a parent selector?

The element>element selector is used to select elements with a specific parent. Note: Elements that are not directly a child of the specified parent, are not selected.


4 Answers

Use length to check it there are elements in the selector, and closest() would be better than parents() as it stops once it finds a match:

if(! $(".myElem").closest(".myDiv").length ) {
    console.log("has no parent with the class .myDiv")
}
like image 167
adeneo Avatar answered Oct 19 '22 15:10

adeneo


If you are testing whether the element with class myElem has a direct parent with class myDiv use the following test

if(!$(".myElem").parent().hasClass("myDiv")) {
    console.log("test")
};
like image 40
Arun P Johny Avatar answered Oct 19 '22 14:10

Arun P Johny


if($(".myElem").parent().hasClass(".myDiv")) {
    console.log("has a parent with the class .myDiv")
}
else
{
    console.log("no parent class .myDiv found")
}
like image 3
IT ppl Avatar answered Oct 19 '22 14:10

IT ppl


This should select those elements that have got class myElem with a parent that has a class myDiv:

$(".myElem").filter(function(elem) {
    return $(this).parents(".myDiv").length
});

or this should select those elements that have got class myElem and does not have a parent that has a class myDiv:

$(".myElem").filter(function(elem) {
    return !$(this).parents(".myDiv").length
});
like image 1
Zoltan.Tamasi Avatar answered Oct 19 '22 15:10

Zoltan.Tamasi