Indu
Indu

Reputation: 37

why can't I insert text object into an element's innerHTML

we can assign the input value to a variable and then we're assingning that variable to an element's innerHTML, likewise why can't I insert text object into an element's innerHTML??

eg code:

x = document.getElementById("my_input"). value;
    
y = document.createElement("p");
    
y.innerHTML = x;

This code works but the below code isn't, why?

eg code:

x = document.getElementById("my_input"). value;
    
    
y = document.createElement("p");
    
z = document.createTextNode("x");
    
y.innerHTML = z;

I'm a beginner in js.. Correct me if I'm wrong..thanks!!

Upvotes: 2

Views: 661

Answers (1)

Daniel Cruz
Daniel Cruz

Reputation: 2295

as you can read here: https://www.w3schools.com/jsref/prop_html_innerhtml.asp The innerHTML property can only be set to a string. Because z is a DOM object then it wont work as you expect. To add a DOM object you must use the appendChild method. You can read more here: https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild

It all comes down to types. One propery is of type string so you should not pass an object to it.

const x = document.getElementById("myInput").value;

const y = document.createElement("p");

const z = document.createTextNode(x);

// you need to append child, cause x is a DOM object, not a string
y.appendChild(z);

// just to show that the element actually worked
document.getElementById("myElement").appendChild(y);
<input id="myInput" value="Hello world" /><br /> Div element:
<div id="myElement">

</div>

Upvotes: 1

Related Questions