Javascript создать элемент внутри элемента

Node: appendChild() method

The appendChild() method of the Node interface adds a node to the end of the list of children of a specified parent node.

Note: If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position.

If the given child is a DocumentFragment , the entire contents of the DocumentFragment are moved into the child list of the specified parent node.

appendChild() returns the newly appended node, or if the child is a DocumentFragment , the emptied fragment.

Note: Unlike this method, the Element.append() method supports multiple arguments and appending strings. You can prefer using it if your node is an element.

Syntax

Parameters

The node to append to the given parent node (commonly an element).

Return value

A Node that is the appended child ( aChild ), except when aChild is a DocumentFragment , in which case the empty DocumentFragment is returned.

Exceptions

Thrown when the constraints of the DOM tree are violated, that is if one of the following cases occurs:

  • If the parent of aChild is not a Document , DocumentFragment , or an Element .
  • If the insertion of aChild would lead to a cycle, that is if aChild is an ancestor of the node.
  • If aChild is not a DocumentFragment , a DocumentType , an Element , or a CharacterData .
  • If the current node is a Text , and its parent is a Document .
  • If the current node is a DocumentType and its parent is not a Document , as a doctype should always be a direct descendant of a document.
  • If the parent of the node is a Document and aChild is a DocumentFragment with more than one Element child, or that has a Text child.
  • If the insertion of aChild would lead to Document with more than one Element as child.
Читайте также:  Html select one checkbox only

Description

If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position — there is no requirement to remove the node from its parent node before appending it to some other node. This means that a node can’t be in two points of the document simultaneously. The Node.cloneNode() method can be used to make a copy of the node before appending it under the new parent. Copies made with cloneNode are not automatically kept in sync.

appendChild() returns the newly appended node, instead of the parent node. This means you can append the new node as soon as it’s created without losing reference to it:

const paragraph = document.body.appendChild(document.createElement("p")); // You can append more elements to the paragraph later 

On the other hand, you cannot use appendChild() in a fluent API fashion (like JQuery).

// This doesn't append three paragraphs: // the three elements will be nested instead of siblings document.body .appendChild(document.createElement("p")) .appendChild(document.createElement("p")) .appendChild(document.createElement("p")); 

Example

Append a paragraph to the body

// Create a new paragraph element, and append it to the end of the document body const p = document.createElement("p"); document.body.appendChild(p); 

Creating a nested DOM structure

In this example, we attempt to create a nested DOM structure using as few temporary variables as possible.

const fragment = document.createDocumentFragment(); const li = fragment .appendChild(document.createElement("section")) .appendChild(document.createElement("ul")) .appendChild(document.createElement("li")); li.textContent = "hello world"; document.body.appendChild(fragment); 

It generates the following DOM tree:

section> ul> li>hello worldli> ul> section> 

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 13, 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.

Источник

Как создать вложенный элемент в JS?

А как вложить внутрь созданного списка его элементы? Покажите пожалуйста наглядный пример, а если есть что почитать, ткните что и где.

svupol

Советую прочитать здесь все, а если именно по вашей теме, то вот

var ul = document.createElement("ul"); ul.classList.add("ul"); var li = document.createElement('li'); li.innerHTML = 'Какой-то текст'; ul.appendChild(li) document.body.appendChild(ul); // Или же можно записать так, более удобный способ для добавления множества тегов. document.body.innerHTML = ` `

weranda

Спасибо, бегло уже читал, но не понял о вложенности элементов.
Т. е. сначала создаем элемент, потом добавляем его на страницу, потом создаем еще один элемент и добавляем его на страницу. Правильно?
Если правильно, то какой-то замкнутый круг получается. Можно ли создать все и сразу, а потом добавить все на страницу или только такой вариант?

svupol

weranda, обновите страницу. А так, если вам нужно создать более одного тега, то зачастую делают разметку в виде строки. И добавляют примерно так ->

const dom = ` ` document.body.innerHTML = dom

Источник

Javascript создать элемент внутри элемента

Для создания элементов объект document имеет следующие методы:

  • createElement(elementName) : создает элемент html, тег которого передается в качестве параметра. Возвращает созданный элемент
  • createTextNode(text) : создает и возвращает текстовый узел. В качестве параметра передается текст узла.
var elem = document.createElement("div"); var elemText = document.createTextNode("Привет мир");

Таким образом, переменная elem будет хранить ссылку на элемент div . Однако одного создания элементов недостаточно, их еще надо добавить на веб-страницу.

Для добавления элементов мы можем использовать один из методов объекта Node:

  • appendChild(newNode) : добавляет новый узел newNode в конец коллекции дочерних узлов
  • insertBefore(newNode, referenceNode) : добавляет новый узел newNode перед узлом referenceNode

Используем метод appendChild:

      

Заголовок статьи

Первый абзац

Второй абзац

Сначала создаем обычный элемент заголовка h2 и текстовый узел. Затем текстовый узел добавляем в элемент заголовка. Затем заголовок добавляем в один из элементов веб-страницы:

Добавление элемента в JavaScript

Однако нам необязательно для определения текста внутри элемента создавать дополнительный текстовый узел, так как мы можем воспользоваться свойством textContent и напрямую ему присвоить текст:

var elem = document.createElement("h2"); elem.textContent = "Привет мир";

В этом случае текстовый узел будет создан неявно при установке текста.

Теперь рассмотрим, как аналогичный элемент добавить в начало коллекции дочерних узлов блока div:

var articleDiv = document.querySelector("div.article"); // создаем элемент var elem = document.createElement("h2"); // создаем для него текст var elemText = document.createTextNode("Привет мир"); // добавляем текст в элемент в качестве дочернего элемента elem.appendChild(elemText); // получаем первый элемент, перед которым будет идти добавление var firstElem = articleDiv.firstChild.nextSibling; // добавляем элемент в блок div перед первым узлом articleDiv.insertBefore(elem, firstElem);

Если нам надо вставить новый узел на второе, третье или любое другое место, то нам надо найти узел, перед которым надо вставлять, с помощью комбинаций свойств firstChild/lastChild и nextSibling/previousSibling.

Копирование элемента

Иногда элементы бывают довольно сложными по составу, и гораздо проще их скопировать, чем с помощью отдельных вызовов создавать из содержимое. Для копирования уже имеющихся узлов у объекта Node можно использовать метод cloneNode() :

var articleDiv = document.querySelector("div.article"); // клонируем элемент articleDiv var newArticleDiv = articleDiv.cloneNode(true); // добавляем в конец элемента body document.body.appendChild(newArticleDiv);

В метод cloneNode() в качестве параметра передается логическое значение: если передается true, то элемент будет копироваться со всеми дочерними узлами; если передается false — то копируется без дочерних узлов. То есть в данном случае мы копируем узел со всем его содержимым и потом добавляем в конец элемента body.

Клонирование элементов в JavaScript

Удаление элемента

Для удаления элемента вызывается метод removeChild() объекта Node. Этот метод удаляет один из дочерних узлов:

var articleDiv = document.querySelector("div.article"); // находим узел, который будем удалять - первый параграф var removableNode = document.querySelectorAll("div.article p")[0]; // удаляем узел articleDiv.removeChild(removableNode);

В данном случае удаляется первый параграф из блока div

Замена элемента

Для замены элемента применяется метод replaceChild(newNode, oldNode) объекта Node. Этот метод в качестве первого параметра принимает новый элемент, который заменяет старый элемент oldNode, передаваемый в качестве второго параметра.

var articleDiv = document.querySelector("div.article"); // находим узел, который будем заменять - первый параграф var oldNode = document.querySelectorAll("div.article p")[0]; // создаем элемент var newNode = document.createElement("h2"); // создаем для него текст var elemText = document.createTextNode("Привет мир"); // добавляем текст в элемент в качестве дочернего элемента newNode.appendChild(elemText); // заменяем старый узел новым articleDiv.replaceChild(newNode, oldNode);

В данном случае заменяем первый параграф заголовком h2:

Источник

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