简体   繁体   中英

How to check if any div has inner div having specific class say 'xyz' using javascript?

<div class="abc">
  <a><img></a>
  <h4></h4>
  <div class="xyz">
    <a href="google.com">Hello</a>
  </div>
</div>

in above html code how do i check whether div having class abc has div having class xyz .

You can simply do this:

var list = document.querySelectorAll('div.abc div.xyz');
if (1 == list.length) {
    alert("found");
}

Here's a demo: http://jsfiddle.net/3xQ5X/

使用JQuery:

$("div.abc").has("div.xyz");

Try something like this: Get your parent div an id like abc.

var v =  document.getElementById('abc');
for(var i in v.children)
{
 if( v.children[i].nodeName == 'DIV')//this will tell if the parent div has children divs
 {
  console.log(v.children[i].className == 'xyz');//this will be true if the child div has a class named xyz.
 }
}

Also remember to modify this script according to your requirement. I mean you can give an specific class in place of id to the divs you want to traverse. To select all the divs containing some specific class, use this link 's function.

This script will do the needful.

<script type="text/javascript">
$(document).ready(function(){

    if($("div.abc").children('div').hasClass("xyz"))
    {
        alert("found");
    }

});
</script>

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