JavaScript

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.

Append Child 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 >

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.

Must Read: JavaScript insertBefore() Method

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 >

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.

Conclusion

I hope now you have a complete understanding of how to append a child node in HTML using JavaScript. The appendChild method will help you to append the child element at the end of the list of elements.

Happy Coding 🙂

Nachiket Panchal

Founder & Administrator of `errorsea` Having interest in Programming & Technology.

Recent Posts

5 Important Things To Know About WordPress Before You Use It

There is a reason big-name companies like CNN use WordPress. WordPress is a popular content…

3 years ago

How to Install MySQL on Your PC in 3 Easy Steps

In this tutorial, I'm going to show you how to install MySQL on your computer.…

5 years ago

Download and Install Turbo C++ for Windows 10 (Full Installation Guide)

Download Turbo C++ for windows 10 in just 7 Mb and run your first C++…

5 years ago

PHP .HTACCESS Redirects

We can redirect any webpage to any other or redirect the whole domain or website…

5 years ago

PHP Redirect Pages

There are lots of methods to redirect pages, like refresh-redirect from META tag, redirect from…

5 years ago

PHP Include & Required

Include files in PHP are used in appending various global or config files. We can…

5 years ago