JavaScript outerHTML Property Tutorial

In this section, we will learn what the outerHTML property is and how to use it in JavaScript.

What is Element outerHTML Property in JavaScript?

The JavaScript Element outerHTML property is used to get or set the entire content of an element that is invoking this property.

When we say the entire content of an HTML element, that means even the opening and closing tags, attributes and the content within the body will return if we call this property.

Also, for setting a new content, you should know that this content will replace the element itself and not just its content within the body.

For example, you might have an <h1> element and want to replace it with an <h2> with some content; So all you need to do is to get a reference to that <h1> element and invoke the outerHTML property and assign the new source code as the value of this property. After that, the <h1> will be gone and you’ll see the <h2> and its content replaced the <h1> and its children.

JavaScript outerHTML Property Syntax:

element.outerHTML;

element.outerHTML = “newValue”;

JavaScript outerHTML Property Input Value

The value we set for this property is the new source that will replace the element that is invoking this property (Along with its content, of course).

JavaScript outerHTML Property Return Value

The return value of this property is the entire content (Including the opening and closing tags and attributes as well as the content within the body) of the element that is invoking this property.

Example: using outerHTML Property in JavaScript

See the Pen using outerHTML Property in JavaScript by Omid Dehghan (@odchan1) on CodePen.

Leave a Reply