views:

79

answers:

5

Is there a way to determine when the contents of a HTML tag has changed? I would prefer to catch an event rather than polling it.

My use case is I have text enclosed in span tags within a rich text editor, and I need to remove the span tags when the enclosing text is modified by the user.

A: 

could you give me a better idea of what you are trying to achieve, as the last answer seems like the right idea... however obviously you want something else to happen

Eddie
A: 

I don't think there is an event available (except for input elements), however you could poll it.

$element = $('#my-element');

var originalHtml = $element.html();

var pollHtml = setInterval(function() {

    if (originalHtml !== $element.html()) {
        alert('HTML changed!'); 
        clearInterval(pollHtml);
    };

}, 100);
alex
there are thousands of these span tags so polling just won't be practical
Plumo
A: 

I can't add a comment so I'm putting my suggestion here,

@Justin Johnson

$("#close-question-2114317").change(function() {alert(1);}); 
$("#close-question-2114317").text( function(){
    $(this).trigger('change'); 
    return "Close!!!";
});

I believe we can call the trigger if that's the case...

Reigel
A: 

You must be using JavaScript to modify the DOM in some way. Polling is in most cases a bad idea. I have set up a demo here that gives you a good idea on how you might want to check the HTML for changes. Just call that function when needed... even if it is just polling.

Jabes88
+3  A: 

Are you using one of the typical WYSIWYG editors, and don't want to update their code to break updatability? Then maybe you could listen to the onTextChange event (or something similar) that the WYSIWYG editor is sending, check the contents of the change, and react on that.

Just an idea, given that you give a bit too little information in your question.

Emil Stenström
yeah that's probably the best solution. It's a pity I can't receive more events from structural tags like span.
Plumo