html appendchild code example
Example 1: JavaScript append text to div
var div = document.getElementById('myElementID');
div.innerHTML += "Here is some more data appended";
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
Example 4: how to appendChild in the begin of the div javascript
var element = document.getElementById("div1");
element.insertBefore(para, element.firstChild);
Example 5: appendchild javascript
const parent = document.createElement('div');
const child = document.createElement('p');
const appendValue = parent.append(child);
console.log(appendValue) // undefined
const appendChildValue = parent.appendChild(child);
console.log(appendChildValue) // <p><p>