0

Is there a way to observe my html body?

I have a css class: .abdala and this script:

<script type="text/javascript">
    $(document).ready(function () {
        $(".abdala").each(function (e) {
            alert("Abdala css class found");
        });
    });
</script>

I need observe the html body changes.

If i do that:

$(document.body).append("<div class=\"abdala\">another abadala element</div>");

After append i need do something. Is there a way to do that?

Trxplz0
  • 371
  • 1
  • 2
  • 13
  • 1
    There's a hardly usable API called `MutationObserver` in case you're interested: http://addyosmani.com/blog/mutation-observers/ - cannot recommend to use that in production though. – m90 Aug 01 '14 at 18:56

4 Answers4

1

This was answered in another question

How to detect new element creation in jQuery?

It looks like there is a plugin for it, but it seems pretty bad since its not native to jQuery. It could really effect performance because the browser has to use more resources to keep checking for an element change.

AngularJS is perfect for that kind of operation, but jQuery isn't.

Community
  • 1
  • 1
Justin Workman
  • 380
  • 3
  • 6
0

There isn't a listener to do this, but you can create a setInterval and check regularly:

var oldBody = $('body').html();
function check() {
    if (oldBody != $('body').html()) {
        alert('Body html changed');
        oldBody = $('body').html();
    }
}

setInterval(check, 10); // checks every 10 milliseconds
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
0

I believe this stackoverflow answer is what you are looking for.

However, I don't recommend it.

If you have something else that needs to be done after appending then just do it.

$(document.body).append("<div class=\"abdala\">another abadala element</div>");

callNextFunctionHere();

Why go to more trouble than this ?

Community
  • 1
  • 1
TchiYuan
  • 4,258
  • 5
  • 28
  • 35
0

If you know the class/id of the element AND have control when it changes, you could simple subscribe to the "change" event after the update.

HTML

<span class="abcd"> something</span>
<div id="log"></div>
<button id="change">change</button>

JavaScript

(function () {
    // basic helper to log when changes happen
    var log = function (message) {
        $("#log").append(message);
    };

    // the event that triggers the change
    $('#change').on('click', function (e) {
        $('.abcd').append('...more').trigger('change');
    });

    // the event that riggers the change
    $('.abcd').on('change', function (e) {
        log(new Date().toJSON() + ": this has changed</br>");
    });

})();

JsFiddle http://jsfiddle.net/anAgent/xyzDL/1/

anAgent
  • 2,550
  • 24
  • 34
  • Buyer beware: `The change event is fired for , – m90 Aug 01 '14 at 19:27