moessi774 moessi774 - 1 month ago 6
TypeScript Question

Javascript/Typescript generated HTML not showing correctly

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

Answer

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);