Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
169
rated 0 times [  173] [ 4]  / answers: 1 / hits: 18273  / 8 Years ago, mon, april 11, 2016, 12:00:00

I want to detect changes in div-elements. I tried already the addEventListener with some types (e.g.: change, load).



Here is my example, but the event won't trigger:



<!doctype html>
<html>
<head>
</head>
<body>
<div id='DivElement'>Test Div Text...</div>
<button type=button onclick=EditDivElement()>click me!</button>

<script>
function EditDivElement() {
ClickCounter++;
SelectedDiv.textContent=new text content: + ClickCounter;
}

function OnDivEdit() {
alert(success!);
}

var ClickCounter = 0;
var SelectedDiv = document.querySelector(#DivElement);

SelectedDiv.addEventListener(change, OnDivEdit);
</script>
</body>
</html>


(Edit: It's for a browser-addon and it should be used on other websites.)


More From » javascript

 Answers
14

You can use a MutationObserver.



From MDN:



// select the target node
var target = document.querySelector('#some-id');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.type);
});
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };

// pass in the target node, as well as the observer options
observer.observe(target, config);

// later, you can stop observing
observer.disconnect();





Note: Deprecated



What I have done in the extensions I wrote was to listen on DOMNodeInserted.



div.addEventListener(DOMNodeInserted, function (e) {
e.target //
}, false);

[#62605] Sunday, April 10, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
citlalia

Total Points: 138
Total Questions: 104
Total Answers: 87

Location: Iceland
Member since Sat, Sep 17, 2022
2 Years ago
;