@georapbox/mutation-observer-element
v2.0.0
Published
A custom element that offers a declarative interface to the MutationObserver API.
Downloads
9
Maintainers
Readme
<mutation-observer>
A custom element that offers a declarative interface to the MutationObserver API.
Install
$ npm install --save @georapbox/mutation-observer-element
Usage
Script
import { MutationObserverElement } from './node_modules/@georapbox/mutation-observer-element/dist/mutation-observer.js';
// Manually define the element.
MutationObserverElement.defineCustomElement();
Alternatively, you can import the automatically defined custom element.
import './node_modules/@georapbox/mutation-observer-element/dist/mutation-observer-defined.js';
Markup
<mutation-observer
attr="*"
attr-old-value
char-data
char-data-old-value
child-list
>
<button class="btn-primary">Click to mutate me</button>
</mutation-observer>
API
Properties
| Name | Reflects | Type | Default | Description |
| ---- | -------- | ---- | ------- | ----------- |
| attr
| ✓ | String | null
| A string of attribute names to be monitored. To monitor specific attributes' changes, separate them by a space, eg title class href
. To monitor all attributes' changes, use *
. |
| attrOldValue
attr-old-value
| ✓ | Boolean | false
| Set to true
to record the previous value of any attribute that changes when monitoring the node or nodes for attribute changes. |
| childList
child-list
| ✓ | Boolean | false
| Set to true
to monitor the target node for the addition of new child nodes or removal of existing child nodes. |
| charData
char-data
| ✓ | Boolean | false
| Set to true
to monitor the specified target node for changes to the character data contained within the node or nodes. |
| charDataOldValue
char-data-old-value
| ✓ | Boolean | false
| Set to true
to record the previous value of a node's text whenever the text changes on nodes being monitored. |
| disabled
| ✓ | Boolean | false
| Set to true
to stop monitoring for mutations. |
All of the above properties reflect their values as HTML attributes to keep the element's DOM representation in sync with its JavaScript state.
NOTE: From the properties above, at least one of
attr
,child-list
orchar-data
must be present, otherwise, no changes are monitored and no mutation events are emitted.
Slots
| Name | Description | | ---- | ----------- | | (default) | The element(s) to observe for mutations. |
Events
mutation-observer:mutate
- Emitted when the element is mutated. A list of MutationRecord objects is attached to event.detail
, with information about how the target element has been changed.
document.querySelector('mutation-observer').addEventListener('mutation-observer:mutate', evt => {
console.log(evt.detail); // => { mutationList: [MutationRecord] }
});
Changelog
For API updates and breaking changes, check the CHANGELOG.
Browser support
Browsers without native custom element support require a polyfill.
- Firefox
- Chrome
- Microsoft Edge
- Safari