WebSurfer WebSurfer - 4 months ago 7
Javascript Question

Universal function to create elements and append to parent (seems like cannot convert string -> object)

Hi,

I couldn't find the answer, so I decided to ask by myself, though I believe it should be easy and had been discussed many times..
Maybe I just don't know how it should be searched..


Situation: I want to create and use universal javascript function with which I can easily create new childs to parent nodes.

Look how I want it:

<!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(elementType,clickedId) {
var newElement = document.createElement(elementType);
newElement.innerHTML = 'new element';
clickedId.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 (clickedId == "someThing"){
someThing.appendChild(newElement);
}
if (clickedId == "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.

Please, let me know how to fix it! Big thanks!

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.