appendchild dom code example

Example 1: javascript append to paragraph

// In the JS script

var parElement = document.getElementById("myPar");
var textToAdd = document.createTextNode("Text to be added");
parElement.appendChild(textToAdd);

//In the HTML file

<p id="myPar"></p>

Example 2: appendchild javascript

function createMenuItem(name) {
    let li = document.createElement('li');
    li.textContent = name;
    return li;
}
// get the ul#menu
const menu = document.querySelector('#menu');
// add menu item
menu.appendChild(createMenuItem('Home'));
menu.appendChild(createMenuItem('Services'));
menu.appendChild(createMenuItem('About Us'));

Example 3: appendchild javascript

const parent = document.createElement('div');
const child = document.createElement('p');
// Appending Node Objects
parent.append(child) // Works fine
parent.appendChild(child) // Works fine
// Appending DOMStrings
parent.append('Hello world') // Works fine
parent.appendChild('Hello world') // Throws error