How to get HTML string of dynamically modified element using jQuery?

$(document).ready(function() {
  var parent = $('#foo');
  parent.find('#bar').val('hi');
  console.log(parent.prop('outerHTML'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
  <input type='text' id="bar" value="" />
</div>
Run codeHide result

I have a container div with a child input element, the initial value is empty, after that I change its value using jQuery and try to get the modified html string using .prop ('outerHTML'). However, it returns:

<div id="foo"><input type="text" id="bar" value=""></div>

I need to return it as:

<div id="foo"><input type="text" id="bar" value="hi"></div>

Is it possible?

+4
source share
3 answers

You can use instead .attr().

$(document).ready(function() {
  var parent = $('#foo');
  parent.find('#bar').attr('value', 'hi');
  console.log(parent.prop('outerHTML'));

  $('#txt').text('hello');
  console.log($('#par').find('#txt').prop('outerHTML'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
  <input type='text' id="bar" value="" />
</div>

<div id="par">
  <textarea id='txt'></textarea>
</div>
Run codeHide result

More details - visit the link.

+4
source

Of course, use a direct attrbite change, not an element value.

$(document).ready(function() {
  var parent = $('#foo');
  parent.find('#bar').attr('value', 'hi');
  console.log(parent.prop('outerHTML'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
  <input type='text' id="bar" value="" />
</div>
Run codeHide result
+1
source

$(document).ready(function() {
  var parent = $('#foo');
  parent.find('#bar').attr('value','hi');
  console.log(parent.prop('outerHTML'));
});
0

Source: https://habr.com/ru/post/1670508/


All Articles