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

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. The myFunction uses the getElementbyId function to fetch the element with the given id and then fetches that elements outerHTML. If an id is given such that there are multiple HTML elements with that id or there are none, then the outerHTML will throw an error as its being called on a null value.

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

<div id="demo">
    <p>This is the text inside</p>
</div>

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

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


 Output:

<p id="demo">This is the text inside</p>



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.