Benjoe
Benjoe

Reputation: 466

A condition to determine if the parent container child elements contains of specific class and do something

This is what I've tried so far. But nothing of the three workaround works.

I've tried using hasClass and find but no luck to make it work.

HTML:

<div>Click me (I have a .cute class)
    <p class="cute"></p>
</div>

<div>Click me (I don't a .cute class)
    <p class="no-cute-class"></p>
</div>

jQuery:

$(document).ready(function(){
    $("div").click(function(){
        //Looking for siblings if has class of cute
        if($(this).siblings().hasClass('cute')) {
             alert("Found cute class");
        } else {
             alert("Didn't found cute class");
        }

        //jQuery hasClass
        if($(this).hasClass('cute')) {
             alert("Found cute class");
        } else {
             alert("Didn't found cute class");
        }

        //Using jQuery find
        if($(this).find('.cute')) {
            alert("Found cute class");
        } else {
            alert("Didn't found cute class");
        }
    });
});

Upvotes: 0

Views: 423

Answers (3)

Atal Prateek
Atal Prateek

Reputation: 541

If you want to use hasClass try this:

$(document).ready(function(){
  $("div").click(function(){
    if($(this).find("p").hasClass("cute")){
      alert("has cute");
    }
    else{
      alert("no class");
    }

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <div>Click me (I have a .cute class)
    <p class="cute"></p>
  </div>
  <div>Click me (I don't a .cute class)
    <p class="no-cute-class"></p>
  </div>

Upvotes: 0

Shubham Baranwal
Shubham Baranwal

Reputation: 2498

You can't wrap div inside of p tag.

Because it renders in browser like below -

<p> <div> test </div> </p>

rendered in the DOM as:

<p> </p> <div> test </div> <p> </p>

You can also use span instead of div like below or try JSFiddle

HTML Code-

<div>
  <p>Click me (I have a .cute class)
    <span class="cute"></span>
  </p>

  <p>Click me (I don't a .cute class)
    <span class="no-cute-class"></span>
  </p>
</div>

JS Code-

$("p").click(function() {
  if ($(this).find('.cute').length) {
    alert("Found Cute Class");
  } else {
    alert("Didn't found cute class");
  }
});

Upvotes: 2

SilentCoder
SilentCoder

Reputation: 2000

I hope you want to search whether class called .cute is inside your element. But you can not traverse from p to a div. better change as below and try.

You can use length to find out any related class is there.

$("div").click(function(){
  if($(this).find('.cute').length > 0){
      alert('has class');
  }
  else{
      alert("no class");
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>Click me (I have a .cute class)
    <span class="cute"></span>
</div>

<div>Click me (I don't a .cute class)
    <span class="no-cute-class"></span>
</div>

Upvotes: 4

Related Questions