Reputation: 419
I want to create a new element and then set the value of the new element. Then add the element to div.
var x = document.getElementById("Header");
var element =document.createElement("test");
var addel=x.appendChild(element)
<div id="Header">
<h1>
<img height="150" src="http://test.com/im.jpeg">
<span>test</span>
</h1>
</div>
for instance, create a new element called "test" then add the element to div and set the value of test="1".
Upvotes: 0
Views: 58
Reputation: 347
change the code with
var x = document.getElementById("Header");
var element =document.createElement("test");
element.setAttribute('value','1');
var addel=x.appendChild(element);
Upvotes: 0
Reputation: 480
Your new element won't be recognised by the browser as html has fixed set of elements You perhaps need to use a text based element like span,p or you can simply set innerText of a block element like div to "1" If you want to create your own elements You can refer here https://developers.google.com/web/fundamentals/web-components/customelements You can also extend existing elements to form new elements
Upvotes: 1
Reputation: 68933
You can use Node.textContent
or HTMLElement.innerText
property to set the text:
var x = document.getElementById("Header");
var element =document.createElement("test");
element.textContent = "1";
var addel=x.appendChild(element);
<div id="Header">
<h1>
<img height="150" src="http://test.com/im.jpeg">
<span>test</span>
</h1>
</div>
Upvotes: 0