HTML DOM Element hasChildNodes() method

Definition and usage

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

hasChildNodes() The method is read-only.

Note

Whitespace between nodes is considered child nodes (text nodes).

See also:

childNodes property

firstChild property

lastChild property

nextSibling property

previousSibling property

parentNode property

HTML Node and Element

in HTML DOM(Document Object Model), an HTML document is a collection of nodes that have (or do not have) child nodes.

Noderefers to element nodes, text nodes, and comment nodes.

ElementThe whitespace between them is also a text node.

while the element is just an element node.

Child Node and Child Element

childNodes ReturnsChild Node(element nodes, text nodes, and comment nodes).

children ReturnsChild Element(not text and comment nodes).

Sibling and Element Sibling

Siblingare 'brother' and 'sister'.

Siblingare nodes that have the same parent node (in the same childNodes in the list).

Element Siblingare elements that have the same parent element (in the same children in the list).

Example

Example 1

Does the element have child nodes:

let answer = element.hasChildNodes();

Try It Yourself

Example 2

Remove the first child node of the element:

if (element.hasChildNodes()) {
  element.removeChild(element.childNodes[0]);
}

Try It Yourself

Syntax

element.hasChildNodes()

Parameter

None.

Return Value

Type Description
Boolean Value Returns boolean true if the node has child nodes, otherwise returns false.

Browser Support

element.hasChildNodes() It is a DOM Level 1 (1998) feature.

All browsers fully support it:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support 9-11 Support Support Support Support