简体   繁体   中英

How to find a classname under a specific parent in jquery

I have problem here. Please refer to the html code below:

<div class="main">
    <div class="second1">
        <div class="third1">
            <p></p>
        </div>
    </div>
    <div class="second2">
        <div class="third1">
            <h1></h1>
        </div>      
    </div>
</div>

I want to know which of the class between second1 and second2 has h1 tag. Because I want to alert with "h1 is here" if it is found under second2 else "h1 is not here"

Simply target on $('h1') , then you can use .parent() to grab the parent element, and .attr('class') to grab the class name(s).

This can be seen in the following:

 console.log($('h1').parent().attr('class')); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="main"> <div class="second1"> <div class="third1"> <p></p> </div> </div> <div class="second2"> <div class="third1"> <h1></h1> </div> </div> </div> 

Or , if you specifically want to grab the <h1> tag under .second2 , you can make use of .find() as $('.second2').find('h1') .

This can be seen in the following (slightly-modified) code:

 console.log($('.second2').find('h1').parent().attr('class')); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="main"> <div class="second1"> <div class="third1-in-second1"> <h1></h1> </div> </div> <div class="second2"> <div class="third1-in-second2"> <h1></h1> </div> </div> </div> 

You can check for the presence of a class with .hasClass() , and you'll want to check that the grandparent ( .parent().parent() ) has the class second2 .

This can be seen in the following:

 if ($('h1').parent().parent().hasClass('second2')) { alert('h1 is here'); } else { alert('h1 is NOT here'); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="main"> <div class="second1"> <div class="third1"> <p></p> </div> </div> <div class="second2"> <div class="third1"> <h1></h1> </div> </div> </div> 

let secondClass = $('.main').find('h1').parent().parent().attr('class');
console.log("h1 tag is on" + secondClass);

if(secondClass === "second1"){
    //...
    alert("h1 is in second1");
}else{
    //...
    alert("h1 is in second2");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM