PipBoy2000
PipBoy2000

Reputation: 440

How to get live data from HTML element by JQuery?

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?

Upvotes: 1

Views: 1901

Answers (2)

Rauli Rajande
Rauli Rajande

Reputation: 2020

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>

Upvotes: 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>

Upvotes: 1

Related Questions