Search code examples
javascriptinnerhtml

Return innerHTML inclusive of the tag you're targeting?


I'm trying to return the innerHTML of a tag, inclusive of the tag I'm targeting. Let's say you have this HTML:

<div class="parent">
  <p>Text 1</p>
  <p>Text 2</p>
  <p>Text 3</p>
</div>

And this JS:

const divInner = document.querySelector('.parent').innerHTML
console.log(divInner)

The console log will return only the html inside of the div tags:

  <p>Text 1</p>
  <p>Text 2</p>
  <p>Text 3</p>

Is there a way to return the innerHTML INCLUSIVE of the parent tag (the div), so that the console.log returns this entire section, without creating another parent container outside of the div?:

<div class="parent">
  <p>Text 1</p>
  <p>Text 2</p>
  <p>Text 3</p>
</div>

I know I can do this if I just add another parent div outside the inner div and target the parent div's innerHTML instead, but I'm trying to apply this on a page where adding more divs will screw up the alignment / spacing and I don't wish to readjust it all over again if I can avoid it.


Solution

  • Yes, you can do it using outerHTML.

    The outerHTML attribute of the element DOM interface gets the serialized HTML fragment describing the element including its descendants. It can be set to replace the element with nodes parsed from the given string.

    const divInner = document.querySelector('.parent').outerHTML;
    console.log(divInner);
    <div class="parent">
      <p>Text 1</p>
      <p>Text 2</p>
      <p>Text 3</p>
    </div>