Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

javascript - 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...