When trying to place a value to an already existing element without using document.createElement()
the browser displays the desired result, however, when I do it using document.createElement()
I get [Object HTMLElement]
but no error in the console.
For example, the following code works as intended:
const heading = document.querySelector('#heading');
const headingText = "<em>I am some random text</em>";
heading.insertAdjacentHTML("beforebegin", headingText);
However, if I were to append headingText
to heading element after creating it with document.createElement()
then I get the [Object HTMLElement]
which is unexpected.
const heading = document.querySelector('#heading');
const headingText = document.createElement('em');
headingText.textContent = "I am some random text";
heading.insertAdjacentHTML('beforebegin', headingText);
What is the reason for this?
NOTE: I am not interested in a solution, as I already have one, as can see, I am interested in the reasoning, logic behind what's causing that and why. Thank you.
I have tried googling for an answer, but I was not able to find one. The closest I got was this question here at stackoverflow: `insertAdjacentHTML` and `createElement`
However, that does not answer my question.