HTML DOM Element children property

Definition and usage

children Property returns a collection of child elements of the element.

children Property returns an HTMLCollection object.

See also:

firstElementChild property

lastElementChild property

nextElementSibling property

previousElementSibling property

childElementCount property

childNodes property

HTML nodes and elements

In HTML DOMIn (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 blank spaces between them are also text nodes.

While elements are just element nodes.

Child nodes and child elements

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

children ReturnsChild elements(not text and comment nodes).

Siblings and element siblings

słodycze rodzeństwaTo 'brother' and 'sister'.

słodycze rodzeństwato węzły posiadające tego samego rodzica (w tym samym childNodes na liście).

słodycze rodzeństwato elementy posiadające tego samego rodzica (w tym samym children na liście).

Przykład

Przykład 1

Pobierz zbiór podelementów elementu <body>:

const collection = document.body.children;

Spróbuj sam

Przykład 2

Ile podelementów ma "myDIV":

let count = document.getElementById("myDIV").children.length;

Spróbuj sam

Przykład 3

Zmień tło drugiego podelementu "myDIV":

const collection = document.getElementById("myDIV").children;
collection[1].style.backgroundColor = "yellow";

Spróbuj sam

Przykład 4

Pobierz tekst trzeciego podelementu <select> (indeks 2):

const collection = document.getElementById("mySelect").children[2].text;

Spróbuj sam

Przykład 5

Przeszukaj wszystkie podelementy <body> i zmień ich tło:

const collection = document.body.children;
for (let i = 0; i < collecton.length; i++) {
  collection[i].style.backgroundColor = "red";
}

Spróbuj sam

Gramatyka

element.children

Zwrócona wartość

Typ Opis
Obiekt

Obiekt HTMLCollection.

Zbiór węzłów elementów.

Elementy są sortowane według kolejności ich występowania w dokumencie.

Wsparcie przeglądarek

element.children To jest cecha DOM Level 1 (1998).

Wszystkie przeglądarki wspierają je w pełni:

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