JavaScript node.hasChildNodes() Method
You are Here:
JavaScript node.hasChildNodes() Method
The node.hasChildNodes()
method indicates whether the given Node has child nodes or not.
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<p>Do p tag has a child?</p>
<button onclick="myFunction()">Check Here</button>
<script>
var x = document.getElementsByTagName("p")[0];
function myFunction(){
alert(x.hasChildNodes());
}
</script>
</body>
</html>
Syntax
node.hasChildNodes()
Return Values
Value | Explanation |
---|---|
true | The node has child nodes. |
false | The node has no child nodes. |
Real Time Example
In the following example, before deleting the first child from the specified parent node, we first check whether the specified parent node has any child node in it.
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<ul><li>Honda</li><li>Yamaha</li></ul>
<button onclick="myFunction()">Remove Child</button>
<script>
var x = document.getElementsByTagName("ul")[0];
function myFunction(){
if(x.hasChildNodes())
x.removeChild(x.childNodes[0]);
else
alert("No child found in ul tag");
}
</script>
</body>
</html>
Reminder
Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.
We are working to cover every Single Concept in JavaScript.
Please do google search for:
Join Our Channel
Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.
This channel is primarily useful for Full Stack Web Developer.