JavaScript’s Node.hasChildNodes()
method returns a Boolean value indicating whether the Node
has child nodes or not.
Syntax
Node.hasChildNodes();
Parameters
None.
Return value
A Boolean value that is true
if the node has child nodes and false
if the node has no child nodes.
Examples
Here is an example of using the JavaScript hasChildNodes()
method. Suppose have the following lists of animals:
<ul id="list">
<li>Cat</li>
<li>Dog</li>
<li>Horse</li>
</ul>
We would like to examine whether the ul
element has child nodes or not with JavaScript.
An easy way to do that is to select the element with the getElementById()
method and use the hasChildNodes()
method:
let list = document.getElementById('list');
console.log(list.hasChildNodes());
You should now be able to see the answer to our question in the console of your browser.
Browser compatibility
Chrome
|
Edge
|
Firefox
|
Internet Explorer
|
Opera
|
Safari
|
Chrome (Android)
|
Firefox (Android)
|
Opera (Android)
|
Safari (iOS)
|
Samsung Internet
|
WebView (Android)
|
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
hasChildNodes() |
1 | 12 | 1 | 6 | 12.1 | 1 | 18 | 4 | 12.1 | 1 | 1.0 | 4.4 |