The onchange event doesn't track changes to the DOM. Fortunately JavaScript offers a pretty powerful API that does this job: MutationObserver.
Usage is pretty simple:
Reference the element you want to track for changes
var target = document.getElementsByClassName('class1');
Create a new instance of MutationObserver
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type == "childList") {
console.log("an element has been added!");
}
});
});
Tell it to track changes to the DOM - which is done by the childList property
var config = {
childList: true,
};
and start observing
observer.observe(target[0], config);
Here's a complete example:
var target = document.getElementsByClassName('class1');
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type == "childList") {
console.log("an element has been added!");
}
});
});
var config = {
childList: true,
};
observer.observe(target[0], config);
function addDiv() {
var theDiv = document.createElement("div");
theDiv.innerText = "I'm a div";
target[0].appendChild(theDiv);
}
<div class="class1">
<input name="in" />
</div>
<button onclick="addDiv()">
Add
</button>