WebSurfer WebSurfer - 4 months ago 6
Javascript Question

Universal function to create children elements and append to parent nodes

I want to create and use universal javascript function with which it should be easy to create new children to parent nodes.

I want to achieve:

<!DOCTYPE html>
<html>
<body>

<style>
div {
border: 2px solid #eeeeee;
background-color: #dff0d8;
}
ol {
background-color: #dff0d8;
}
li {
background-color: #eff0c8;
}
</style>

<script>
function addNewElement(newElementType,parentId) {
var newElement = document.createElement(newElementType);
newElement.innerHTML = 'new element';
parentId.appendChild(newElement);
// actually I want to use just this simple code, what makes this function universal, but it doesn't work..
// while next commented lines work as it should
/**
if (parentId == "someThing"){
someThing.appendChild(newElement);
}
if (parentId == "list"){
list.appendChild(newElement);
}
**/
}
</script>

<p>In next example we can add new child element to this list:</p>
<ol id="list">
<li>1</li>
<li>2</li>
<li>3</li>
</ol>
<button onclick="addNewElement('li','list')">Add new li-element to this list</button>
<p>In next example we can add new child element to this div:</p>
<div id="someThing">Something here</div>
<button onclick="addNewElement('div','someThing')">Add new div-element to this div</button>
</body>
</html>


I guess it should be simple even without any jQuery or other libraries.

How can I achieve this?

Answer

First of all, you shouldn't use the same element ID more than once.

According to W3C:

The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).

So I changed your HTML, i.e. removed IDs from buttons and passed required IDs into addNewElement function:

<p>In next example we can add new child element to this list:</p>
<ol id="list">
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ol>
<button onclick="addNewElement('li', 'list')">Add new li-element to this list</button>
<p>In next example we can add new child element to this div:</p>
<div id="someThing">Something here</div>
<button onclick="addNewElement('div', 'someThing')">Add new div-element to this div</button>

Then I updated addNewElement function:

function addNewElement(elementType, parentId) {
    let parentElement = document.getElementById(parentId);
    let newElement = document.createElement(elementType);

    newElement.innerHTML = 'new element';
    parentElement.appendChild(newElement);
}

And it works.

Please look at the jsFiddle for more details.

Comments