Javascript getting first child

HTML DOM Element firstElementChild

Get the tag name of the first child element of «myDIV»:

Get the text of the first child element of a element:

Description

The firstElementChild property returns the first child element of the specified element.

The firstElementChild property is read-only.

The firstElementChild property returns the same as children[0].

See Also:

Nodes vs Elements

In the HTML DOM terminology:

Nodes are all nodes (element nodes, text nodes, and comment nodes).

Whitespace between elements are also text nodes.

Elements are only element nodes.

childNodes vs children

childNodes returns child nodes (element nodes, text nodes, and comment nodes).

children returns child elements (not text and comment nodes).

firstChild vs firstElementChild

firstChild returns the first child node (an element node, a text node or a comment node). Whitespace between elements are also text nodes.

firstElementChild returns the first child element (not text and comment nodes).

lastChild vs lastElementChild

lastChild returns the last child node (an element node, a text node or a comment node). Whitespace between elements are also text nodes.

Читайте также:  Ширина макета

lastElementChild returns the last child element (not text and comment nodes).

Syntax

Return Value

Browser Support

element.firstElementChild is a DOM Level 3 (2004) feature.

It is fully supported in all modern browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 11

Источник

Element: firstElementChild property

The Element.firstElementChild read-only property returns an element’s first child Element , or null if there are no child elements.

Element.firstElementChild includes only element nodes. To get all child nodes, including non-element nodes like text and comment nodes, use Node.firstChild .

Value

Examples

ul id="list"> li>First (1)li> li>Second (2)li> li>Third (3)li> ul> script> const list = document.getElementById("list"); console.log(list.firstElementChild.textContent); // logs "First (1)" script> 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 7, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

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

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

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

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

Сверху: documentElement и body

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

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

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

В частности, если скрипт находится в , document.body в нём недоступен, потому что браузер его ещё не прочитал.

Поэтому, в примере ниже первый alert выведет null :

        

В DOM значение null значит «не существует» или «нет такого узла».

Дети: childNodes, firstChild, lastChild

Здесь и далее мы будем использовать два принципиально разных термина:

  • Дочерние узлы (или дети) – элементы, которые являются непосредственными детьми узла. Другими словами, элементы, которые лежат непосредственно внутри данного. Например, и являются детьми элемента .
  • Потомки – все элементы, которые лежат внутри данного, включая детей, их детей и т.д.

    (и несколько пустых текстовых узлов):

    и вложенные в них:
    (ребёнок

      ) и (ребёнок
      ) – в общем, все элементы поддерева.

    Коллекция childNodes содержит список всех детей, включая текстовые узлы.

    Пример ниже последовательно выведет детей document.body :

    Обратим внимание на маленькую деталь. Если запустить пример выше, то последним будет выведен элемент . На самом деле, в документе есть ещё «какой-то HTML-код», но на момент выполнения скрипта браузер ещё до него не дошёл, поэтому скрипт не видит его.

    Свойства firstChild и lastChild обеспечивают быстрый доступ к первому и последнему дочернему элементу.

    Они, по сути, являются всего лишь сокращениями. Если у тега есть дочерние узлы, условие ниже всегда верно:

    elem.childNodes[0] === elem.firstChild elem.childNodes[elem.childNodes.length - 1] === elem.lastChild

    Для проверки наличия дочерних узлов существует также специальная функция elem.hasChildNodes() .

    DOM-коллекции

    Как мы уже видели, childNodes похож на массив. На самом деле это не массив, а коллекция – особый перебираемый объект-псевдомассив.

    И есть два важных следствия из этого:

    for (let node of document.body.childNodes) < alert(node); // покажет все узлы из коллекции >

    Это работает, потому что коллекция является перебираемым объектом (есть требуемый для этого метод Symbol.iterator ).

    alert(document.body.childNodes.filter); // undefined (у коллекции нет метода filter!)

    Первый пункт – это хорошо для нас. Второй – бывает неудобен, но можно пережить. Если нам хочется использовать именно методы массива, то мы можем создать настоящий массив из коллекции, используя Array.from :

    alert( Array.from(document.body.childNodes).filter ); // сделали массив

    DOM-коллекции, и даже более – все навигационные свойства, перечисленные в этой главе, доступны только для чтения.

    Мы не можем заменить один дочерний узел на другой, просто написав childNodes[i] = . .

    Для изменения DOM требуются другие методы. Мы увидим их в следующей главе.

    Почти все DOM-коллекции, за небольшим исключением, живые. Другими словами, они отражают текущее состояние DOM.

    Если мы сохраним ссылку на elem.childNodes и добавим/удалим узлы в DOM, то они появятся в сохранённой коллекции автоматически.

    Коллекции перебираются циклом for..of . Некоторые начинающие разработчики пытаются использовать для этого цикл for..in .

    Не делайте так. Цикл for..in перебирает все перечисляемые свойства. А у коллекций есть некоторые «лишние», редко используемые свойства, которые обычно нам не нужны:

       

    Соседи и родитель

    Соседи – это узлы, у которых один и тот же родитель.

    • говорят, что – «следующий» или «правый» сосед
    • также можно сказать, что «предыдущий» или «левый» сосед .

    Следующий узел того же родителя (следующий сосед) – в свойстве nextSibling , а предыдущий – в previousSibling .

    Родитель доступен через parentNode .

    // родителем является alert( document.body.parentNode === document.documentElement ); // выведет true // после идёт alert( document.head.nextSibling ); // HTMLBodyElement // перед находится alert( document.body.previousSibling ); // HTMLHeadElement

    Навигационные свойства, описанные выше, относятся ко всем узлам в документе. В частности, в childNodes находятся и текстовые узлы и узлы-элементы и узлы-комментарии, если они есть.

    Но для большинства задач текстовые узлы и узлы-комментарии нам не нужны. Мы хотим манипулировать узлами-элементами, которые представляют собой теги и формируют структуру страницы.

    Поэтому давайте рассмотрим дополнительный набор ссылок, которые учитывают только узлы-элементы:

    Эти ссылки похожи на те, что раньше, только в ряде мест стоит слово Element :

    • children – коллекция детей, которые являются элементами.
    • firstElementChild , lastElementChild – первый и последний дочерний элемент.
    • previousElementSibling , nextElementSibling – соседи-элементы.
    • parentElement – родитель-элемент.

    Свойство parentElement возвращает родитель-элемент, а parentNode возвращает «любого родителя». Обычно эти свойства одинаковы: они оба получают родителя.

    За исключением document.documentElement :

    alert( document.documentElement.parentNode ); // выведет document alert( document.documentElement.parentElement ); // выведет null

    Причина в том, что родителем корневого узла document.documentElement ( ) является document . Но document – это не узел-элемент, так что parentNode вернёт его, а parentElement нет.

    Эта деталь может быть полезна, если мы хотим пройти вверх по цепочке родителей от произвольного элемента elem к , но не до document :

    while(elem = elem.parentElement) < // идти наверх до alert( elem ); >

    Изменим один из примеров выше: заменим childNodes на children . Теперь цикл выводит только элементы:

    Источник

    HTML DOM Element firstChild

    Get the text of the first child node of a element:

    Description

    The firstChild property returns the first child node of a node.

    The firstChild property returns a node object.

    The firstChild property is read-only.

    The firstChild property is the same as childNodes[0] .

    Important!

    firstChild returns the first child node: An element node, a text node, or a comment node.

    Whitespace between elements are also text nodes.

    Alternative:

    The firstElementChild property returns the first child element (ignores text and comment nodes).

    See Also:

    Node Properties

    Nodes vs Elements

    In the HTML DOM terminology:

    Nodes are all nodes (element nodes, text nodes, and comment nodes).

    Whitespace between elements are also text nodes.

    Elements are only element nodes.

    childNodes vs children

    childNodes returns child nodes (element nodes, text nodes, and comment nodes).

    children returns child elements (not text and comment nodes).

    firstChild vs firstElementChild

    firstChild returns the first child node (an element node, a text node or a comment node). Whitespace between elements are also text nodes.

    firstElementChild returns the first child element (not text and comment nodes).

    lastChild vs lastElementChild

    lastChild returns the last child node (an element node, a text node or a comment node). Whitespace between elements are also text nodes.

    lastElementChild returns the last child element (not text and comment nodes).

    Syntax

    Return Value

    More Examples

    This example demonstrates how whitespace may interfere.

    Try to get the node name of the first child node of «myDIV»:

    Looks like first child

    Looks like last Child

    However, if you remove the whitespace from the source, there are no #text nodes in «myDIV»:

    Browser Support

    element.firstChild is a DOM Level 1 (1998) feature.

    It is fully supported in all browsers:

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

    Источник

Оцените статью