0

I am a basic JavaScript hacker and not an advanced programmer and I would appreciate some pointers.

I am after a JavaScript (or JQuery) function that can monitor the DOM and alter if the content within a specified DIV has been changed. I want this new content captured in a variable for further processing (but for now should be echoed to console.log or alert to demonstrate success).

The DIV is content that will be updated by a separate AJAX process or may contain an iFrame, neither of which I will have full control over. The content may be updated multiple times and on an infrequent and unstructured basis. The contents of the DIV may also change format and could contain any sort of content.

I believe I need a JS event to handle this (rather than any sort of interval based check) and I have been looking at the DOMsubtreeModified function, but not only can't I make it work consistently, it appears that this is not reliable across browsers and I need this to work regardless of the client.

Am I barking up the wrong tree? Is this possible in a cross-browser way? Should I continue to hack on DOMSubtreeModified to try and get it working or is there a better method?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Peter Gross
  • 213
  • 2
  • 4
  • 14
  • possible duplicate of [DOM Mutation event in JQuery or vanilla Javascript](http://stackoverflow.com/questions/7692730/dom-mutation-event-in-jquery-or-vanilla-javascript) – Barmar Feb 24 '14 at 17:11
  • http://stackoverflow.com/questions/2844565/is-there-a-jquery-dom-change-listener?lq=1 (I'm not sure if it's a strict "duplicate", but I think it's very similar in intent; YMMV with the actual application) – user2864740 Feb 24 '14 at 17:12
  • Yes, this does appear to be a duplicate - I just wasn't asking the question the right/same way. Thanks anyway, they're useful pointers. – Peter Gross Feb 24 '14 at 17:37

1 Answers1

1

DOMSubtreeModified is the right event.

This might help you, I created it after reading your question. I think it does what you want it to do.

<div class="change_event_box">
  1234
</div>

<script>
$(document).ready(function() {
  $('.change_event_box').bind("DOMSubtreeModified",function(){
    alert('changed');
  });

  setTimeout(function() {
    $('.change_event_box').text("4321");
  }, 5000);
});
</script>

http://jsfiddle.net/F4FMk/

Jacob
  • 1,483
  • 8
  • 13