Mike
Mike

Reputation: 51

How to add Elements to DOM

I need a function which creates element and than adds text to that element and than adds that new element to a some location in DOM. I am noob to this. I find this function but I don't know how to automaticaly specify location so that I can just call function and for example specify third argument as an element to which I want to append new element.

function appendElement (elemNode,textNode) {
            var element = document.createElement(elemNode);
            var text = document.createTextNode(textNode);
            element.appendChild(text);
            document.body.appendChild(element);
}
appendElement("b","lorem");

Upvotes: 3

Views: 5321

Answers (4)

user4284772
user4284772

Reputation:

function appendElement (elemNode,textNode,containerToAppend) {
    var container = document.getElementById(containerToAppend);
    var element = document.createElement(elemNode);
    var text = document.createTextNode(textNode);
    element.appendChild(text);
    container.appendChild(element);
}
appendElement("p","this is text","ContainerId");

Upvotes: 1

GOTO 0
GOTO 0

Reputation: 47614

Here's a way to do it in one line:

function appendElement (elemNode, textContent, parent) {
    parent.appendChild(document.createElement(elemNode)).textContent = textContent;
}

appendElement("b","lorem", document.getElementById("container"));
div { background-color: aqua }
<div id="container"></div>

Upvotes: 1

MarsOne
MarsOne

Reputation: 2186

Here is my attempt. Completely ripped off from developer.Mozilla.org with a minor tweak.

JSFIDDLE DEMO

Javascript:

function addElement() {
    // Create a new div element  and give it some content 
    var newDiv = document.createElement("div");
    var newContent = document.createTextNode("Hi there and greetings!");
    newDiv.appendChild(newContent); //Add the text node to the newly created div. 

    // Add the newly created element and its content into the Parent of the clicked button
    var parentDiv = event.target.parentNode;
    document.body.insertBefore(newDiv, parentDiv);
}

HTML

<div id="div1">
    <input type="button" onclick="addElement(event)" value="Click me to add div" />
</div>
<div id="div2">
    <input type="button" onclick="addElement(event)" value="Click me to add div" />
</div>
<div id="div3">
    <input type="button" onclick="addElement(event)" value="Click me to add div" />
</div>

Upvotes: 0

Syed Arif Iqbal
Syed Arif Iqbal

Reputation: 1427

function appendElement (elemNode,textNode,containerToAppend) {
        var container = document.getElementById(containerToAppend);
        var element = document.createElement(elemNode);
        var text = document.createTextNode(textNode);
        element.appendChild(text);
        container.appendChild(element);
}
appendElement("b","lorem","ContainerId");

Upvotes: 2

Related Questions