1

I want to fire an action when there is change in html content. Below code changes html content of myId element, when click on button, so there is change in html content of myId now I want to fire another action say console.log("myalert").

<html>
<body>
    <input type="button" id="buttonid" value="click">
    <div id = "myId">
    </div>
</body>
<script>
var button = document.getElementById("buttonid");
    button.addEventListener("click", function () {
        console.log("alert");
        document.getElementById('myId').innerHTML = '<input type="button" id="button3" value="click2">'
    });

var button2 = document.getElementById("myId");
button2.addEventListener("change", function () {
        console.log("myalert");        
    });    
</script>
</html>

How can I achieve my requirement?

Note: I don't want to use jQuery.

user3002180
  • 431
  • 6
  • 19

1 Answers1

0

There is no real event for that. You could however resolve this by listening for changes in an interval loop. I wouldn't really recommend it, but it's not up to me to decide what you use in the end. It would be something in the lines of:

var myIdContent = document.getElementById('myId').innerHTML;
setInterval(function(){
  if(myIdContent !== document.getElementById('myId').innerHTML){
    myIdContent = document.getElementById('myId').innerHTML;
    // Element has changed, do some modifications here
  }
}, 1000); // Lower number for shorter intervals

However this could become terribly slow when the contents of the div grows. A better way would be to invoke an event or 'change' function whenever you change html from javascript. You have more stuff to write, but also more control over when change events occur.

Question with answers that don't involve comparing contents: Detect changes in the DOM

Community
  • 1
  • 1
Hless
  • 3,326
  • 20
  • 22
  • I don't want to use `setInterval`. Is there any other way? – user3002180 Feb 04 '14 at 16:01
  • Well then, there's no real easy ready made implementation of DOM manipulation events. You should check here, and be willing to get your hands dirty: http://stackoverflow.com/questions/3219758/detect-changes-in-the-dom – Hless Feb 04 '14 at 16:03