Tom
Tom

Reputation: 12998

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.

Upvotes: 16

Views: 39906

Answers (7)

Marc Nicole
Marc Nicole

Reputation: 389

the only solution that works if $('.myElem') has more than one element is the one from Zoltan

see the example here

 var takeElements = $('.myElement').filter(function(){
   return $(this).closest('.bannedAncestors').length === 0
 });
 
 takeElements.css('color','green');
 
 var bannedElements = $('.myElement').filter(function(){
   return $(this).closest('.bannedAncestors').length !== 0
 });
 
 bannedElements.css('color','red');
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="bannedAncestors">
  <div> number of nested element don't matters
    <div class="myElement">
      don't take this child since it has an ancestor we don't want
    </div>
  </div>
</div>
<div>
  <div>
    <div class="myElement">
      but this one is ok
    </div>
  </div>
</div>

Upvotes: 2

Sanjay
Sanjay

Reputation: 1745

A better approach is to use .closest() if you know the classname of the child.

if(!$('yourtag.childClass').closest('yourParentTag').hasClass('classname')){
    console.log('does not exist');
}

Upvotes: 0

Zoltan.Tamasi
Zoltan.Tamasi

Reputation: 1391

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
});

Upvotes: 1

adeneo
adeneo

Reputation: 318372

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")
}

Upvotes: 29

karthick
karthick

Reputation: 6178

Try this one.

   if($("#child").parent("span#parent").length > 0)
   {
          console.log("parent is span");

   }
   else {
          console.log("parent is not span or no parent");
   }

Upvotes: 0

IT ppl
IT ppl

Reputation: 2647

if($(".myElem").parent().hasClass(".myDiv")) {
    console.log("has a parent with the class .myDiv")
}
else
{
    console.log("no parent class .myDiv found")
}

Upvotes: 3

Arun P Johny
Arun P Johny

Reputation: 388446

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")
};

Upvotes: 6

Related Questions