Oussama EL ATTAOUI
PRO
2 weeks ago
Oussamacountry asked

Whats the difference between innerHTML and outerHTML if both select the same HTML element?

Kelish Rai
Expert
2 weeks ago
Kelish Rai answered

The difference between innerHTML and outerHTML is in what part of the element they work with.

  • innerHTML gives you just the content inside an element.

  • outerHTML gives you the entire element itself, including the tag.

Consider this code:

Hello

And this JavaScript:

const hero = document.querySelector(".demo");

Now if you do:

console.log(hero.innerHTML);

You'll get:

Hello

But if you do:

console.log(hero.outerHTML);

You'll get:

Hello

So, outerHTML includes the entire element, while innerHTML only includes what's inside it.

Simply put, use innerHTML if you want to change the content inside an element, and use outerHTML if you want to change the element itself.

This question was asked as part of the JavaScript in Browser course.