-1

I am trying to use Vanilla JS; to display the date and time when an html element is updated.

So for instance when the content changed within my:

<li class="active"></li>

I know jQuery has quick methods to identify via selectors, i.e.

$('li.active').bind("DOMSubtreeModified",function(){
    alert('changed');
});

but i need a plain vanilla JS solution.

Dr Upvote
  • 8,023
  • 24
  • 91
  • 204
  • 3
    Possible duplicate of [Detect changes in the DOM](https://stackoverflow.com/questions/3219758/detect-changes-in-the-dom) – Heretic Monkey Mar 05 '19 at 21:26
  • 1
    You can still use that. Attach it to the element instead of the document and that will isolate it. – Get Off My Lawn Mar 05 '19 at 21:29
  • it's better to subscribe upstream to the JS stuff that actually changes the markup, instead of sniffing mutation side-effects, which are fragile and performance-robbing. – dandavis Mar 05 '19 at 21:33
  • 1
    There is at least [one answer that demonstrates using this at the element level](https://stackoverflow.com/a/50493861/215552)... – Heretic Monkey Mar 05 '19 at 21:35

2 Answers2

1

Use a mutation observer to watch the list item instead of watching the document as a whole.

// The item we want to watch
var watch = document.querySelector('.active')

// The new observer with a callback to execute upon change
var observer = new MutationObserver((mutationsList) => {
  console.log(new Date().toUTCString())
});

// Start observing the element using these settings
observer.observe(watch, { childList: true, subtree: true });

// Some random test function to modify the element
// This will make sure the callback is running correctly
setInterval(() => {
  watch.innerHTML = Math.random() * 1000
}, 1000)
<ul>
  <li class="active"></li>
</ul>
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
-2

Most jQuery code has a similar counterpart available. The $('li.active') can be replaced with document.querySelectorAll('li.active'). This gives you all elements matching your selector. The bind call would be achieved by iterating over the elements and using addEventListener('DOMSubtreeModified', function(event) { … }).

Christoph Herold
  • 1,799
  • 13
  • 18