js add element into elem code example

Example 1: js add more text to element

document.getElementById("p").textContent += " This is the text from javascript.";

<p id ="p">This is the text from HTML.</p>

Example 2: Inserting HTML elements with JavaScript

function create(htmlStr) {
    var frag = document.createDocumentFragment(),
        temp = document.createElement('div');
    temp.innerHTML = htmlStr;
    while (temp.firstChild) {
        frag.appendChild(temp.firstChild);
    }
    return frag;
}

var fragment = create('<div>Hello!</div><p>...</p>');
// You can use native DOM methods to insert the fragment:
document.body.insertBefore(fragment, document.body.childNodes[0]);