Languages
[Edit]
EN

jQuery - get outer html

8 points
Created by:
Root-ssh
175020

Using jQuery it is possible to get outer HTML source code in the following ways.

1. jQuery prop method example

// ONLINE-RUNNER:browser;

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
  <div id="element">
    <h3>Head 1</h3>
    <p>Some apostrophe text...</p>
    <h3>Head 2</h3>
    <p>Some apostrophe text...</p>
  </div>
  <script>

    $(document).ready(function() {
        var element = $('#element');
      	var html = element.prop('outerHTML');
      
        console.log(html);
    });

  </script>
</body>
</html>

2. Element outerHTML property

Example 1

// ONLINE-RUNNER:browser;

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
  <div id="element">
    <h3>Head 1</h3>
    <p>Some apostrophe text...</p>
    <h3>Head 2</h3>
    <p>Some apostrophe text...</p>
  </div>
  <script>

    $(document).ready(function() {
        var elements = $('#element');
      	var html = elements[0].outerHTML;
      
        console.log(html);
    });

  </script>
</body>
</html>

Note:

  • by using elements[0] first DOM element that has been found by jQuery is acessed
  • elements[0] is equal to result from document.getElementById('element') and document.querySelector('element') method calls.

Example 2

// ONLINE-RUNNER:browser;

<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
  <div class="element">
    <h3>Head 1.1</h3>
    <p>Some apostrophe text...</p>
    <h3>Head 1.2</h3>
    <p>Some apostrophe text...</p>
  </div>
  <div class="element">
    <h3>Head 2.1</h3>
    <p>Some apostrophe text...</p>
    <h3>Head 2.2</h3>
    <p>Some apostrophe text...</p>
  </div>
  <script>

    $(document).ready(function() {
        var elements = $('.element');

        var html = '';

      	elements.each(function(index, element) {
            html += element.outerHTML;
        });
      
        console.log(html);
    });

  </script>
</body>
</html>

Note:

  • element represents pure DOM element object - without jQuery cover logic

See also

  1. JavaScript - what is difference between inner and outer html?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

jQuery

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join