css-observe
css-observe is a "web component as a service" that specializes in watching for DOM elements matching a CSS selector appearing within the same Shadow DOM realm (or within a specified "closest" selector). When such an element is spotted, css observe can perform up to four distinct actions:
- Fire an event.
- Perform a DTR transform on the newly discovered element ("target").
- Perform a DTR transform on the host's shadow DOM (or document when outside any shadow DOM).
- Perform an action contained within a script tag contained nearby (preferably before).
API Reference
<div>
<script id=my-script nomodule be-exporting>
export const action = (target) => {
target.setAttribute('I am here', '');
}
</script>
<css-observe observe selector="div[test]" data-name="Clive" script-ref=my-script options='{
"targetTransform": {
"span": "dataset.name"
},
"hostTransform":{
"section": [{},{},{},"<span>found it</span>"]
}
}'>
</css-observe>
<div test>
I am here, <span></span>
</div>
<section></section>
</div>
Another attribute / property, within-closest/withinClosest, restricts matches to those within the closest ancestry of the css-observe element matching the within-closest value.
css-observe will fire event: latest-match-changed, and the newly added element can be obtained from event.detail.value.
It will only observe the selector within the same Shadow DOM realm where the element is placed. If the element is placed outside any ShadowDOM, it will observe the selector only outside any ShadowDOM.
Implementation
Based off of an idea found here. I agree: How cool is that?
Viewing Your Element
$ npm install
$ npm run serve
Running Tests
$ npm run test