user9398938
user9398938

Reputation:

How do I create new elements in html?

I want to create new elements when clicking a button. I want my elements to look a certain way.

<ul id="protptypeList">
<li id="element1">
<div style="display: inline-block; width: 33%;">
  <h1>1</h1>
</div>
<div style="display: inline-block; width: 33%;">
  <h1>2</h1>
</div>
<div style="display: inline-block; width: 33%;">
  <h1>3</h1>
</div>
</li>
</ul> 
<div class="btn" onClick="addAnother()"> ADD ELEMENT </div>

My javascript

addAnother = function() {
var ul = document.getElementById("protptypeList");
var li = document.createElement("li");
var children = ul.children.length + 1
li.setAttribute("id", "element"+children)
li.appendChild(document.createTextNode('<div style="display: inline-block; width: 33%;">'
  +'<h1>1</h1>'
+'</div>'
+'<div style="display: inline-block; width: 33%;">'
  +'<h1>2</h1>'
+'</div>'
+'<div style="display: inline-block; width: 33%;">'
  +'<h1>3</h1>'
+'</div>'));
ul.appendChild(li)
}

This attempt only gives me that as text on my element.

How do I create new element that looks like the old ones?

Upvotes: 1

Views: 48

Answers (1)

samanime
samanime

Reputation: 26527

You can't use createElement or createTextNode to turn a string of HTML into an element.

The easiest way to do that is to simply set innerHTML:

li.innerHTML = "<div style="...">...</div>";

That will just put your HTML into the li. If you have other content in your li already and you want to add the HTML, just do this:

li.innerHTML += "<div style="...">...</div>";

createTextNode() doesn't create an element from text, it creates a TextNode which is just simply text without an element. For example:

Array.prototype.forEach.call(document.querySelector('div').childNodes, el => { console.log( el.nodeType, el.data || el.innerText); });
<div>
 This is a text node
 <p>This is a paragraph</p>
 This is more text
</div>

Notice the different nodeType values. 3 is TEXT_NODE and 1 is ELEMENT_NODE. createTextNode() creates the first type.

Upvotes: 1

Related Questions