Biswas Khayargoli
Biswas Khayargoli

Reputation: 1024

How to get HTML string of dynamically changed 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>

I have a container div with child input element, the initial value is empty, after that I change it's value using jQuery and try to get the changed 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 this possible ?

Upvotes: 4

Views: 1695

Answers (3)

Vitaliy Ryaboy
Vitaliy Ryaboy

Reputation: 478

try this

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

Upvotes: 0

kind user
kind user

Reputation: 41893

You can use .attr() instead.

$(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>

For more details - visit following link.

Upvotes: 4

VadimB
VadimB

Reputation: 5711

Sure, use direct attrbite change, not 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>

Upvotes: 1

Related Questions