Can I make getElementById reactive?

I want to use document.getElementById () as signal. Is it possible?
4 Replies
Unknown User
Unknown User16mo ago
Message Not Public
Sign In & Join Server To View
musiclover
musiclover16mo ago
Should I update the signal manaully byself whenever the element is removed or added?
Unknown User
Unknown User16mo ago
Message Not Public
Sign In & Join Server To View
Joe Pea
Joe Pea16mo ago
The only problem is: how do you know when it changes? - Use MutationObserver on the document, observe all children, check if the signal needs to be updated in the MutationObserver callback - make a requestAnimationFrame loop (ugh) and check the result every frame, then set the signal The rAF way is probably easier, but MutationObserver is snappier and not running endlessly.
function elementById(id) {
const [el, setEl] = createSignal(null)

const o = new MutationObserver(() => {
setEl(document.getElementById(id))
})

o.observe(document, {
subtree: true,
childList: true,
})
}

const someEl = elementById('someEl')

createEffect(() => {
console.log('someEl', someEl())
})
function elementById(id) {
const [el, setEl] = createSignal(null)

const o = new MutationObserver(() => {
setEl(document.getElementById(id))
})

o.observe(document, {
subtree: true,
childList: true,
})
}

const someEl = elementById('someEl')

createEffect(() => {
console.log('someEl', someEl())
})
This only works on document. If you are in a ShadowRoot, you have to call shadowRoot.getElementById
Want results from more Discord servers?
Add your server
More Posts