Чем является childnodes в elem childnodes
Перейти к содержимому

Чем является childnodes в elem childnodes

  • автор:

Навигация по DOM-элементам

DOM позволяет нам делать что угодно с элементами и их содержимым, но для начала нужно получить соответствующий DOM-объект.

Все операции с DOM начинаются с объекта document . Это главная «точка входа» в DOM. Из него мы можем получить доступ к любому узлу.

Так выглядят основные ссылки, по которым можно переходить между узлами DOM:

Поговорим об этом подробнее.

Сверху: documentElement и body

Самые верхние элементы дерева доступны как свойства объекта document :

<html> = document.documentElement Самый верхний узел документа: document.documentElement . В DOM он соответствует тегу <html> . <body> = document.body Другой часто используемый DOM-узел – узел тега <body> : document.body . <head> = document.head Тег <head> доступен как document.head .

Нельзя получить доступ к элементу, которого ещё не существует в момент выполнения скрипта.

Walking the DOM

The DOM allows us to do anything with elements and their contents, but first we need to reach the corresponding DOM object.

All operations on the DOM start with the document object. That’s the main “entry point” to DOM. From it we can access any node.

Here’s a picture of links that allow for travel between DOM nodes:

Let’s discuss them in more detail.

On top: documentElement and body

The topmost tree nodes are available directly as document properties:

<html> = document.documentElement The topmost document node is document.documentElement . That’s the DOM node of the <html> tag. <body> = document.body Another widely used DOM node is the <body> element – document.body . <head> = document.head The <head> tag is available as document.head .

A script cannot access an element that doesn’t exist at the moment of running.

In particular, if a script is inside <head> , then document.body is unavailable, because the browser did not read it yet.

So, in the example below the first alert shows null :

In the DOM, the null value means “doesn’t exist” or “no such node”.

Children: childNodes, firstChild, lastChild

There are two terms that we’ll use from now on:

  • Child nodes (or children) – elements that are direct children. In other words, they are nested exactly in the given one. For instance, <head> and <body> are children of <html> element.
  • Descendants – all elements that are nested in the given one, including children, their children and so on.

For instance, here <body> has children <div> and <ul> (and few blank text nodes):

…And descendants of <body> are not only direct children <div> , <ul> but also more deeply nested elements, such as <li> (a child of <ul> ) and <b> (a child of <li> ) – the entire subtree.

The childNodes collection lists all child nodes, including text nodes.

The example below shows children of document.body :

Please note an interesting detail here. If we run the example above, the last element shown is <script> . In fact, the document has more stuff below, but at the moment of the script execution the browser did not read it yet, so the script doesn’t see it.

Properties firstChild and lastChild give fast access to the first and last children.

They are just shorthands. If there exist child nodes, then the following is always true:

There’s also a special function elem.hasChildNodes() to check whether there are any child nodes.

DOM collections

As we can see, childNodes looks like an array. But actually it’s not an array, but rather a collection – a special array-like iterable object.

There are two important consequences:

  1. We can use for..of to iterate over it:

That’s because it’s iterable (provides the Symbol.iterator property, as required).

  1. Array methods won’t work, because it’s not an array:

The first thing is nice. The second is tolerable, because we can use Array.from to create a “real” array from the collection, if we want array methods:

DOM collections, and even more – all navigation properties listed in this chapter are read-only.

We can’t replace a child by something else by assigning childNodes[i] = . .

Changing DOM needs other methods. We will see them in the next chapter.

Almost all DOM collections with minor exceptions are live. In other words, they reflect the current state of DOM.

If we keep a reference to elem.childNodes , and add/remove nodes into DOM, then they appear in the collection automatically.

Collections are iterable using for..of . Sometimes people try to use for..in for that.

Please, don’t. The for..in loop iterates over all enumerable properties. And collections have some “extra” rarely used properties that we usually do not want to get:

Siblings and the parent

Siblings are nodes that are children of the same parent.

For instance, here <head> and <body> are siblings:

  • <body> is said to be the “next” or “right” sibling of <head> ,
  • <head> is said to be the “previous” or “left” sibling of <body> .

The next sibling is in nextSibling property, and the previous one – in previousSibling .

The parent is available as parentNode .

Element-only navigation

Navigation properties listed above refer to all nodes. For instance, in childNodes we can see both text nodes, element nodes, and even comment nodes if they exist.

But for many tasks we don’t want text or comment nodes. We want to manipulate element nodes that represent tags and form the structure of the page.

So let’s see more navigation links that only take element nodes into account:

The links are similar to those given above, just with Element word inside:

  • children – only those children that are element nodes.
  • firstElementChild , lastElementChild – first and last element children.
  • previousElementSibling , nextElementSibling – neighbor elements.
  • parentElement – parent element.

The parentElement property returns the “element” parent, while parentNode returns “any node” parent. These properties are usually the same: they both get the parent.

With the one exception of document.documentElement :

The reason is that the root node document.documentElement ( <html> ) has document as its parent. But document is not an element node, so parentNode returns it and parentElement does not.

This detail may be useful when we want to travel up from an arbitrary element elem to <html> , but not to the document :

Let’s modify one of the examples above: replace childNodes with children . Now it shows only elements:

More links: tables

Till now we described the basic navigation properties.

Certain types of DOM elements may provide additional properties, specific to their type, for convenience.

Tables are a great example of that, and represent a particularly important case:

The <table> element supports (in addition to the given above) these properties:

  • table.rows – the collection of <tr> elements of the table.
  • table.caption/tHead/tFoot – references to elements <caption> , <thead> , <tfoot> .
  • table.tBodies – the collection of <tbody> elements (can be many according to the standard, but there will always be at least one – even if it is not in the source HTML, the browser will put it in the DOM).

<thead> , <tfoot> , <tbody> elements provide the rows property:

What is the difference between children and childNodes in JavaScript?

I have found myself using JavaScript and I ran across childNodes and children properties. I am wondering what the difference between them is. Also is one preferred to the other?

John's user avatar

3 Answers 3

Understand that .children is a property of an Element. 1 Only Elements have .children , and these children are all of type Element. 2

However, .childNodes is a property of Node. .childNodes can contain any node. 3

A concrete example would be:

Most of the time, you want to use .children because generally you don’t want to loop over Text or Comment nodes in your DOM manipulation.

If you do want to manipulate Text nodes, you probably want .textContent instead. 4

1. Technically, it is an attribute of ParentNode, a mixin included by Element.
2. They are all elements because .children is a HTMLCollection, which can only contain elements.
3. Similarly, .childNodes can hold any node because it is a NodeList.
4. Or .innerText . See the differences here or here.

Node.childNodes

The read-only childNodes property of the Node interface returns a live NodeList of child nodes of the given element where the first child node is assigned index 0 . Child nodes include elements, text and comments.

Note: The NodeList being live means that its content is changed each time new children are added or removed.

The items in the collection of nodes are objects, not strings. To get data from node objects, use their properties. For example, to get the name of the first childNode, you can use elementNodeReference.childNodes[0].nodeName .

The document object itself has two children: the Doctype declaration and the root element, typically referred to as documentElement . In HTML documents the latter is the <html> element.

It is important to keep in mind that childNodes includes all child nodes, including non-element nodes like text and comment. To get a collection containing only elements, use Element.children instead.

Value

A live NodeList containing the children of the node.

Note: Several calls to childNodes return the same NodeList .

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *