Metoda HTML DOM Element appendChild()

Definicja i użycie

appendChild() Metoda dodaje węzeł (element) jako ostatniego dziecka elementu.

Zobacz również:

Metoda insertBefore()

Metoda replaceChild()

Metoda removeChild()

Metoda remove()

Atrybut childNodes

Atrybut firstChild

Atrybut lastChild

Atrybut firstElementChild

Atrybut lastElementChild

Powiązane metody dokumentu:

Metoda createElement()

Metoda createTextNode()

Przykład

Przykład 1

Dodawanie elementów do listy:

const node = document.createElement("li");
const textnode = document.createTextNode("Water");
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);

Przed dodaniem:

  • Kawa
  • Herbata

Po dodaniu:

  • Kawa
  • Herbata
  • Woda

Spróbuj sam

Przykład 2

Przenoszenie elementów listy z jednej listy do innej:

const node = document.getElementById("myList2").lastElementChild;
document.getElementById("myList1").appendChild(node);

Przed przesunięciem:

  • Kawa
  • Herbata

  • Woda
  • Mleko

Po przesunięciu:

  • Kawa
  • Herbata
  • Mleko

  • Woda

Spróbuj sam

Przykład 3

Utwórz akapit z tekstem:

  • Utwórz element akapitu
  • Utwórz węzeł tekstowy
  • Dodaj węzeł tekstowy do akapitu
  • Dodaj akapit do dokumentu

Utwórz element <p> i dodaj go do elementu <div>:

const para = document.createElement("p");
const node = document.createTextNode("This is a paragraph.");
para.appendChild(node);
document.getElementById("myDIV").appendChild(para);

Spróbuj sam

Przykład 4

Utwórz element <p> i dodaj go do treści dokumentu:

const para = document.createElement("P");
const node = document.createTextNode("This is a paragraph.");
para.appendChild(node);
document.body.appendChild(para);

Spróbuj sam

Gramatyka

element.appendChild(node)

lub

node.appendChild(node)

Parametr

Parametr Opis
node Wymagane. Węzeł do dodania.

Zwrócony wartość

Typ Opis
Węzeł Dodany węzeł.

Wspierane przeglądarki

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

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

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