JavaScript appendChild() Method

JavaScript appendChild() method appends the new HTML node as the last child of another HTML node. This method is used with JavaScript createElement() method. So if you don’t know how to use createElement() method in JavaScript Please read JavaScript createElement() method.

Example 1

If we have a list in HTML and we want to add an extra item to end of the list, we can use appendChild() method.

<!DOCTYPE html>
<html>
<head>
    <title>Errorsea - JavaScript append child</title>
</head>
<body>

<ul id="languages">
<li>Java</li>
<li>JavaScript</li>
<li>Python</li>
</ul>

<button onclick="append()">Append</button>

<script>
function append() {
var li = document.createElement("li");
li.innerHTML = "Ruby";
document.getElementById("languages").appendChild(li);
}
</script>
</body>
</html>

Explanation:

  • First we create a new <li> element using document.createElement() function.
  • we set it’s innerHTML value to “Ruby”
  • We append this new <li> element inside the <ul> tag.

Example 2

We can also append multiple nodes dynamically.

<!DOCTYPE html>
<html>
<head>
<title>Errorsea - JavaScript append child</title>
</head>
<body>

<div id="container"></div>

<button onclick="append()">Append</button>

<script>
function append() {
var languages = ["Java", "JavaScript", "Python"];

var ul = document.createElement("ul");
for(var i = 0; i < languages.length; i++){
var li = document.createElement("li");
li.innerHTML = languages[i];
ul.appendChild(li);
}
document.getElementById("container").appendChild(ul);
}

</script>
</body>
</html>

Explanation:

  • First we create a new <ul> element using document.createElement() function.
  • After that, we dynamically generate <li> elements and append it to <ul> element.
  • Then we append the <ul> element to <div> element.

Leave a Reply

Your email address will not be published. Required fields are marked *