Convert [Object text] to plain text in JavaScript

383 Views Asked by At

i have following code:

const x = document.createTextNode('Helloooo')
document.body.insertAdjacentText('beforebegin', x) 

and after execution i see something like [object Text].

My question is how do I see the clear text, thus "Helloooo"?

According the documentation:

  • insertAdjacentText (text nodes)
  • insertAdjacentElement (nodes)
  • insertAdjacentHTML (html string)

What does document.createTextNode return? I thought a text node, so I use first method, second doesnt works.

Thx for help.

1

There are 1 best solutions below

3
nullptr On

createTextNode returns a Node, not a string. The second argument to insertAdjacentText should be a string, not a Node:

const x ='Helloooo';
document.body.insertAdjacentText('beforebegin', x);

If you want x to be a Text Node, you can use x.wholeText to get the text of the Node:

document.createTextNode('Helloooo');
document.body.insertAdjacentText('beforebegin', x.wholeText);