Zapp
Zapp

Reputation: 232

javascript checking for child element

Just doing a simple check for a child within my div with an id. But it always returns true regardless if its empty or not. Whats going on?

<html>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<h1 id="number"></h1>
<div id="bigbox">
   <p>Follow us:</p>
   <div id="box">
     <!-- javascript is lying about this div -->    
   </div>
   
</div>
<input id="input" type="button" value="click" />



<script>
$("#input").click(function(){
    var ele = document.getElementById('box');
    if (ele.hasChildNodes()) {
        alert("has");
        alert(ele.hasChildNodes());
    }
    else{
        alert("not");
        alert(ele.hasChildNodes());
    }
}); 
</script>
</html>

Upvotes: 2

Views: 1110

Answers (3)

divy3993
divy3993

Reputation: 5810

Actually i think everything is perfect, but there are White spaces in your div box, so remove the space and try, would solve your problem.

The hasChildNodes() method returns true if the specified node has any child nodes, otherwise false.

Note: Whitespace inside a node is considered as text nodes, so if you leave any white space or line feeds inside an element, that element still has child nodes.

<div id="box"></div> <!-- No space here between start and end -->

CHECK THIS DEMO

Upvotes: 2

oscargilfc
oscargilfc

Reputation: 339

Spaces and line-feeds are text nodes, so it has children. If you don't want to use jQuery, you can simply use:

ele = document.getElementById('box');
if (ele.children.length > 0)) {
    alert("has");
    alert(ele.hasChildNodes());
}
else{
    alert("not");
    alert(ele.hasChildNodes());
}

Upvotes: 1

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Try like this

if ( $('#box').children().length > 0 ) {
     // this div has child and do something
}

Upvotes: 3

Related Questions