Open In App

How to get the outer html of an element using jQuery ?

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, there is a need to get the entire HTML element by its id and not merely its contents, for doing so, we shall use the HTML DOM outerHTML Property to get the outer HTML of HTML element.

Syntax: 

document.getElementById("your-element-id").outerHTML)

You can use a variable and initialize it to the above to get the value of the outer HTML element. Below is an example that illustrates how to fetch the outer HTML element of an HTML element and store it in a variable newVar.

Example 1:  In this example, it has a div that encloses a paragraph with id = “demo”. When the on-screen button is pressed the JavaScript pushes an alert message on the browser window with the outer HTML of the HTML element with the given id. 

HTML




<div id="demo">
    <p>This is the text inside</p>
</div>
<button onclick="myFunction()">Try it</button>
<p id="gfg"></p>
<script>
    function myFunction() {
        var newVar = document.getElementById("demo")
                             .outerHTML;
        document.getElementById("gfg").innerHTML = newVar;
    }
</script>


Output:

How to get the outer html of an element using jQuery ?

How to get the outer html of an element using jQuery ?

Example 2:  This example illustrates that the outerHTML DOM displays only the HTML element whose id is given and not its parent 

HTML




<div>
    <p id="demo">This is the text inside</p>
  
</div>
<p id="gfg"></p>
<button onclick="myFunction()">Try it</button>
  
<script>
    function myFunction() {
        var newVar = document.getElementById("demo")
                             .outerHTML;
         document.getElementById("gfg").innerHTML = newVar;
    }
</script>


 Output:

How to get the outer html of an element using jQuery ?

How to get the outer html of an element using jQuery ?



Last Updated : 15 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads