AppendChild in JavaScript

The ‘appendChild’ method in JavaScript is used to add html elements onto a webpage dynamically. The ‘appendChild’ method is available on every element, as well as the body of the page. This means you can attach elements directly to the body of the page, as top level elements, or nested within other elements.

The below code snippet shows using JavaScript to create a paragraph element, setting some text within the paragraph element, and then adding it to the body of the webpage. Within JavaScript the ‘createElement’ method of the document object is used to create elements of any tag type, the parameter of the function is the name of the tag that will be returned. The ‘innerText’ field of elements can be used to set text values within html tags, html will not be rendered when using this method. If you want to embed and render html then use the ‘innerHTML’ field instead. The final line of the code below gets the body object of the document and calls the ‘appendChild’ method passing in the created paragraph element. This will add the paragraph element to the body of the webpage.

var p = document.createElement("p");
p.innerText = "Hello World";

You can also nest elements within each other using JavaScript, as shown below. A div and paragraph are created, the text of the paragraph is set and then appended to the div, the div is then appended to the body of the document. This results in the div being a top level element with the paragraph inside it, with the text ‘Hello World’ rendered to the page. When an element is appended to the page, or another element, any children of that element will also be appended and render to the page. A child element is an element which is inside another element, and the element it is inside is referred to as the parent element. Within the below example the paragraph would be the child of the div and the div would be the parent of the paragraph element.

var div = document.createElement("div");
var p = document.createElement("p");
p.innerText = "Hello World";

Using the ‘appendChild’ method you are able to dynamically add elements to a webpage. This can allow you to dynamically change the content of the page, or create an entire Single Page Application (SPA). However, creating an entire website using only JavaScript can limit the amount of users that will be able to view and use your site correctly, as some people will disable JavaScript from running on their browser for security or other reasons.

Leave a Reply