Skip to content

An alternative to NodeList which keeps collections up to date when changes to the DOM occur

License

Notifications You must be signed in to change notification settings

molovo/live-node-list

Repository files navigation

LiveNodeList

An alternative to NodeList which keeps collections up to date when changes to the DOM occur

Install

npm install live-node-list

Usage

Use the LiveNodeList constructor anywhere you would normally use document.querySelectorAll().

const items = new LiveNodeList('.item')

LiveNodeList creates a MutationObserver instance to monitor for childList and subtree changes within the parent, and refreshes the list of items whenever the childList changes.

By default, LiveNodeList selects within document.documentElement, but you can limit the scope of the query by passing in a parent element as a second parameter

const items = new LiveNodeList('.item', document.getElementById('my-container'))

LiveNodeList also maintains an internal list of event listeners, and exposes addEventListener() and removeEventListener() methods. Adding an event listener will cascade it to each of the items in the list, and will handle attaching the event listener to new items when the list of items changes.

const fn = () => {}
const items = new LiveNodeList('.item')
items.addEventListener('click', fn)
items.removeEventListener('click', fn)

LiveNodeList also triggers its own update event when the list of items changes. The list of supported events may grow in future.

const items = new LiveNodeList('.item')
items.on('update', (newItems, oldItems) => {
  // Do something
})

About

An alternative to NodeList which keeps collections up to date when changes to the DOM occur

Resources

License

Stars

Watchers

Forks

Packages

No packages published