I need to run a jQuery function on any new <li>
that is appended/added to a <ul>
list, right when it is added. We might start out with:
<ul id="my">
<li></li>
<li></li>
</ul>
After some event on the page but without page-refresh, we have this:
<ul id="my">
<li></li>
<li></li>
<li></li> <!-- Added dynamically -->
</ul>
I want to run a jQuery function on this (and again on any future) new <li>
.
With the .on
function I can catch any change that happens to the wrapping <ul>
:
jQuery('body').on('DOMSubtreeModified', 'ul#my', function() {
...
});
How do I tweak this to catch not any change inside the <ul>
, but to catch the specific <li>
which is being added? Something along the lines of:
jQuery('body').on('DOMSubtreeModified', 'NEW_LI', function() {
NEW_LI.css("background-color", "yellow");
});
The MutationObserver
API is the recommended way to watch DOM modifications. It's easy to integrate, too.
Be sure to inspect the mutation
variable, to get an idea what kind of information you can access.
function createObserver(callback) {
return new MutationObserver(function (mutationRecords) {
mutationRecords.forEach(callback);
});
}
$("ul").each(function () {
var obs = createObserver(function (mutation) {
$(mutation.addedNodes).css("background-color", "yellow");
setTimeout(function () {
$(mutation.addedNodes).css("background-color", "");
}, 1000);
});
obs.observe(this, { childList: true });
});
// ---------------------------------------------------------------
setTimeout(function () {
$("<li>New content appears!</li>").appendTo("ul#my");
}, 2000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="my">
<li>existing content</li>
<li>existing content</li>
<li>existing content</li>
</ul>