Blogs

JavaScript outerHTML

Written by: Zubayr


In this tutorial, I will tell you about outerHTML in javascript. outerHTML provides developers with a lot of power. By this property, you can get whole element value with its HTML Like this:

<textarea></textarea>

1

outerHTML = "

This is a Html element.

";

It is a valid string comprising a combination of text and tags.

There are other properties that can also be used to get the contents of an element such as innerText, innerHTML etc. But outerHTML returns the full HTML code for the element,including the element itself.

This property is not working on some HTML elements such as html, head, body, frameSet, tBody.  When the property is set, the given string simply substitutes the object, including its start and end tags.

Example:

<textarea></textarea>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<html>

<head>

<title>Outerhtml Demo</title>

<style type="text/css">

div.highlightedElement{

background-color: red;

padding: 10px;

}

</style>

 

[removed]

function getValue() {

var oDiv = document.getElementById("div1");

console.log(oDiv.outerHTML);

}

[removed]

</head>

 

<body>

Hello World

<input type="button" value="get HTML" onclick="getValue()" />

</body>

</html>

outerHTML overwrites the element, while innerHTML replaces all children but not the element itself. If there are event handlers on the element, outerHTML also deletes the event handlers.

It is a property of dom/HTMLElementdom/HTMLElement.

Example:

<textarea></textarea>

1

2

3

4

5

6

7

8

9

10

11

  

  <svg width="100" height="100">

  

</svg>

    

<button id = "clearOuter"> Clear all </button>

 

document.getElementById ('clearOuter'). onclick = function () {

   document.getElementById ('figureElem'). outerHTML = '';

console.log (document.getElementById ("figureElem")) // returns zero

}

You can use outerHTML as a wrapper.

Example:

<textarea></textarea>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<style>

.wrapper {border: 2px solid gainsboro}

</style>

 

  <svg width="100" height="100">

  

</svg>

 

<button id = "wrap"> wrap in DIV </button>

[removed]

document.getElementById ("wrap"). onclick = function () {

   let inner = document.getElementById ("inner");

   inner.outerHTML = "

" + inner.outerHTML + "
";

}

[removed]

As we see in the above code outerHTML is the content of an element together with the element itself, outerHTML is working as a wrapper. For example, if an element or an entire part is to be packed into a div element.

Comments
Leave A Comment
Post title