How can we get the outerHTML string of an element together with the values of its descendants?

Lets say we have a tree of div’s,and an arbitrary amount of inputs scattered inside. I know we can do the following to get the outerHTML string of the entire tree :

$(document).on('click', 'button', function() {
  console.log($('#main').get(0).outerHTML);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>LOG outerHTML</button>
<div id="main">
  <input>
  <div><input></div>
  <div></div>
  <div></div>
  <div></div>
  <div><input></div>
  <div>
    <div>
      <div>
        <div><input></div>
      </div>
    </div>
  </div>
</div>

what if we type some text inside the inputs? How can get this ? :

<div id="main">
  <input value="some text">
  <div><input value="some text"></div>
  <div></div>
  <div></div>
  <div></div>
  <div><input value="some text"></div>
  <div>
    <div>
      <div>
        <div><input value="some text"></div>
      </div>
    </div>
  </div>
</div>

Answer

If you want user inputs as input attribute values,then set them yourself:

$(document).on('click', 'button', function() {
  console.log($('#main').get(0).outerHTML);
});



document.addEventListener('input', function (e) {
    e.target.setAttribute("value", e.target.value)
}, false);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>LOG outerHTML</button>
<div id="main">
  <input>
  <div><input></div>
  <div></div>
  <div></div>
  <div></div>
  <div><input></div>
  <div>
    <div>
      <div>
        <div><input></div>
      </div>
    </div>
  </div>
</div>

Leave a Reply

Your email address will not be published. Required fields are marked *