Languages
[Edit]
EN

jQuery - how to get outer html?

8 points
Created by:
Root-ssh
7645

Using jQuery it is possible to get outer html source code in 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.

3. Element outerHTML property 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?
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join