I have tried to make some dynamic HTML. I just want to test if it works and did the following:
let context = document.getElementById(anyDivsId);
let h = document.createElement("H1");
let t = document.createTextNode("hello");
let item = h.appendChild(t);
console.log(item);
context.innerHTML = item;
The console just logs me the plain Text and the InnerHTML of the Div is also just the plain Text and not a HTML element. What am I doing wrong?
EDIT
I really want to show the h1 not the plain text only.
I already changed the context.innerHTML
to context.appendChild
If you're setting the value of innerHTML
, it is a string, not a DOM node.
Either do
let context = document.getElementById(anyDivsId);
context.innerHTML = "<h1>hello</h1>";
Or do..
let context = document.getElementById(anyDivsId);
let h = document.createElement("H1");
let t = document.createTextNode("hello");
h.appendChild(t);
context.appendChild(h);
Try this
let context = document.getElementById(anyDivsId);
context.insertAdjacentHTML('beforeend', '<h1>Hello</h1>');
or
let context = document.getElementById(anyDivsId);
let h = document.createElement("H1");
h.innerText = 'Hello';
context.appendChild(h);
This should work
check the following snippet
window.onload=function(){
let context = document.getElementById('anyDivsId');
let h = document.createElement("h1");
let t = document.createTextNode("hello");
let item = h.appendChild(t);
console.log(item);
context.innerHTML = item;
context.innerText="hello";
}
Hope it helps
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.