Eitanos30
Eitanos30

Reputation: 1439

Isn't text node a child when using children function?

I have the following html code:

 <h1>
      When
      <!-- Green highlight effect -->
      <span class="highlight">banking</span>
      meets<br />
      <span class="highlight">minimalist</span>
    </h1>

And i wrote the following code in js:

    const h1 = document.querySelector('h1');

// Going downwards: child
console.log(h1.childNodes);  //prints text element(**When**)
console.log(h1.children);    // doesn't print text element (**When**)

i understand that children function prints only direct child, but As far as i understand, When is indeed direct child of h1. Can someone explain me if i'm wrong?

Upvotes: 0

Views: 1670

Answers (1)

Quentin
Quentin

Reputation: 944530

Isn't text node a child when using children function?

Yes. Text nodes are nodes and can be child nodes of an element.

doesn't print text element

There's no such thing as a text element (at least in HTML, SVG has one). Element nodes and text nodes are different kinds of nodes.

You're reading too much into the name of the property.

See the MDN documentation:

children is a read-only property that returns a live HTMLCollection which contains all of the child elements

or the specification:

The children attribute’s getter must return an HTMLCollection collection rooted at this matching only element children.

If you want to get all the nodes, including the text nodes, then use childNodes. DOM doesn't need two properties that do the same thing and it is often useful to get just the elements (especially if the only text nodes contain only white space).

Upvotes: 2

Related Questions