Home > Software engineering >  how does JavaScript outerHTML function behave?
how does JavaScript outerHTML function behave?

Time:12-29

I just started learning about DOM Web API and the behavior of outerHTML function seems a bit odd for me.

This is my code:

const heading = document.getElementById('heading');
heading.innerHTML = 'This is a <span>Heading</span>';
console.log(heading.innerHTML);
heading.outerHTML = '<h2>Hello World!</h2>';
console.log(heading.outerHTML);

Output:

This is a <span>Heading</span>
<h1 id="heading">This is a <span>Heading</span></h1>

For what I know DOM changes happen synchronously and therefore I expect the result for the second log to be <h2>Hello World!</h2> but the output is quite confusing.

CodePudding user response:

Ok lets try to give an answer to that step by step.

  • First, you get the elemnet 'heading' ID and assign it to the heading variable.
  • Sets the innerHTML of the heading element ('This is a Head...)
  • Log innerHTML of the heading element.
  • Set outherHTML of heading element (Hello World!.. which replaces the heading element with th enew element in the DOM
  • Log otherHTML of the heading element. BUT , heading element has been replaced in the DOM. OutherHTML property refers to the serialized HTML of the element as it was before, and that is why u see the original tag h1 in the output.

to get what you want, you could try to define a new variable using DOM:

const heading2 = document.getElementById('heading');
console.log(heading2.outerHTML);

this will give you the output ure looking for.

  • Related