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.)
One way to watch for DOM changes in our JavaScript web app is to use the MutationObserver constructor. })(); to create the MutationObserver instance with a loop to append child elements to the body within the async function. We insert a new p element after 1 second 5 times.
Right-click on the search icon button and choose “inspect” to open the Chrome developer tools. Once the dev tools are open, switch to the “Event Listeners” tab and you will see all the event listeners bound to the element. You can expand any event listener by clicking the right-pointing arrowhead.
The addEventListener() method makes it easier to control how the event reacts to bubbling. When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup.
JavaScript Document own method: addEventListener()It does not return any value.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With