Skip to main content

Command Palette

Search for a command to run...

Difference Between InnerHTML and outerHTML

Updated
•2 min read•View as Markdown
Difference Between InnerHTML and outerHTML
P

I'm a self taught web developer and a learner as well. I am sharing my experiences and knowledge here with a hope to help those who are beginners as sharing helps to grow together.

What is innerHTML?

The innerHTML is a DOM element method that is used to get the whole content which is inside the element on which this method is applied. It doesn't return the element on which this method is called but only gives out whole text content within it in the form of a string.

Let's take an example-

<p id="para">Hi! <b> I am Prashant</b></p>

We can call innerHTML method on the p tag by using its id in this way.

para.innerHTML    // Hi! <b> I am Prashant</b>

We not only get the innerHTML but also modify it by assigning the value to it, for example

para.innerHTML = `Hi! I am Rohan`;

In the above assignment I have changed the name from Prashant to Rohan and also removed the bold tag.

What is outerHTML?

The outerHTML is much similar to the innerHTML method. It also return value in the form of the string. It returns the values including the element on which this method is called.

Let's take the above example for better understanding.

<p id="para">Hi! <b> I am Prashant</b></p>

Calling outerHTML method on the p tag

para.outerHTML    // <p id="para">Hi! <b> I am Prashant</b></p>

Similar to the innerHTML method we can also assign values to the elements using outerHTML.

para.outerHTML = `<p id="para">Hi! I am Rohan</p>`;

Similar to the above innerHTML example I have changed the name from Prashant to Rohan and also removed the bold tag.

Conclusion

The innerHTML and outerHTML methods are much similar to each other. The innerHTML method excludes the element on which the method is called. But the outerHTML method includes the element on which it is called.

These methods doesn't valid for text or comment nodes. These methods only work on the element nodes.

More from this blog

PrashantBlogs

35 posts

I'm a self taught web developer and a learner as well. I am sharing my experiences and knowledge here with a hope to help those who are beginners. As sharing helps to grow together.