1

Element

<span class="bar">xxx</span>

contain value and it's updated by Ajax.

I have successfully get this xxx data to variable via JQuery with this script

var foo = $('.bar').html();
$("#other").append("<strong>" + foo  + "</strong>");
// alert(foo) <- for testing

to append it to #other place in page, and it's works fine but... How to get live data (updated by Ajax) from this .bar element?

PipBoy2000
  • 440
  • 7
  • 21

2 Answers2

1

You can use the following:

$('.bar').bind("DOMSubtreeModified",function(){
  $("#other strong").text($(this).text());
});

It will update #other strong when .bar is modified. aka when its updated.

var foo = $('.bar').text();
$("#other").append("<strong>" + foo + "</strong>");


$("button").click(function() {
  $('.bar').text("new data");
})

$('.bar').bind("DOMSubtreeModified",function(){
  $("#other strong").text($(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="bar">xxx</span>

<div id="other"></div>


<button>add new content to bar</button>
Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77
1

Use .on() as .bind() is deprecated!

// to simulate ajax changing contents
$('.ajax').on('keyup', function(){
  $('.first_div').html($(this).val())
})

// your answer
updater();

$('.first_div').on('DOMSubtreeModified', updater)

function updater(){

  var data = $('.first_div').html();
  
  // your logic here
  data = '[' + data + ']'

  // display result
  $('.second_div').html(data)
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<pre>
Enter new content:
<input class="ajax" value="initial">

This is what ajax updates:
<div class="first_div">initial</div>

This is updated by DOMSubtreeModified event:
<div class="second_div"></div>

</pre>
Rauli Rajande
  • 2,010
  • 1
  • 20
  • 24