Get outerHTML of an element with JavaScript/jQuery | Techie Delight

This post will discuss how to get outerHTML of an element in JavaScript and jQuery.

The outerHTML is often used to replace the element and its contents completely. It differs from the innerHTML as innerHTML only represent the HTML of contents of an element, while outerHTML includes the HTML of element itself with its descendants.

1. Using JavaScript

In JavaScript, you can easily get the value of an element’s outerHTML with the outerHTML attribute.

JS

1

2

var

element

=

document

.

getElementById

(

“cc”

)

;

console

.

log

(

element

.

outerHTML

)

;

HTML

1

2

3

<div

id

=

“cc”

>

    

<p>

Content

</p>

</div>

Edit in JSFiddle

2. Using jQuery

With jQuery, you can access the outerHTML attribute of HTML using the $(selector).prop() or $(selector).attr() method.

JS

1

2

3

4

$

(

document

)

.

ready

(

function

(

)

{

    

var

outerHTML

=

$

(

“#cc”

)

.

prop

(

“outerHTML”

)

;

    

console

.

log

(

outerHTML

)

;

}

)

;

HTML

1

2

3

<div

id

=

“cc”

>

    

<p>

Content

</p>

</div>

Edit in JSFiddle

 
Alternatively, you can access the underlying HTML of the object returned by the $(selector) and get its .outerHTML property.

JS

1

2

3

4

$

(

document

)

.

ready

(

function

(

)

{

    

var

outerHTML

=

$

(

“#cc”

)

[

0

]

.

outerHTML

;

    

console

.

log

(

outerHTML

)

;

}

)

;

HTML

1

2

3

<div

id

=

“cc”

>

    

<p>

Content

</p>

</div>

Edit in JSFiddle

That’s all about getting outerHTML of an element in JavaScript and jQuery.