2

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!!

Usitha Indeewara
  • 870
  • 3
  • 10
  • 21
Indu
  • 37
  • 8
  • Because z is a reference to an object, while x (in the first example) is just a string. – Emil Karlsson Feb 08 '22 at 10:02
  • 2
    The value you read from the input field is a string, that you can assign to innerHTML. Your `z` in the second example however is not a string, it is a DOM node. Trying to assign that to innerHTML simply makes little sense. If you want to work with DOM methods, then you need to _append_ your new node to an existing element. – CBroe Feb 08 '22 at 10:03
  • Because z references to an object `[object Text]`. Use `y.appendChild(z)` to add the element as child node. – stacj Feb 08 '22 at 10:03
  • @CBroe: Tq ,but I know these strings but don't have a idea of how the return type of createtextnode looks like..what this createtextnode return looks like ,can you give me a eg – Indu Feb 08 '22 at 12:14
  • It returns the new Text node it created, https://developer.mozilla.org/en-US/docs/Web/API/Text – CBroe Feb 08 '22 at 12:29

1 Answers1

1

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>
Daniel Cruz
  • 1,437
  • 3
  • 5
  • 19