NeoDicereCant
NeoDicereCant

Reputation: 21

Why does inserting an newly created element to an existing element parses [Object HTMLElement]?

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.

Upvotes: 1

Views: 154

Answers (1)

Nijraj Gelani
Nijraj Gelani

Reputation: 1466

The insertAdjacentHTML method takes a string as its second argument which is supposed to be the HTML you want to insert (as in the first example).

But when you pass an object as the second argument, it is converted to a string, (in this case to the string "[Object HTMLElement]") and that is inserted in the DOM.

See also https://www.w3schools.com/jsref/met_node_insertadjacenthtml.asp

Upvotes: 2

Related Questions