Can somebody explain why a StyleSheet
's ownerNode
is null
after I set its textContent
to something?
const style = document.createElement('style')
document.head.appendChild(style)
const sheet = style.sheet
// passes
console.assert(sheet.ownerNode !== null, 'ownerNode is null')
sheet.ownerNode.textContent = 'div { color: red }'
// fails
console.assert(sheet.ownerNode !== null, 'ownerNode is null')
Because by completely replacing the text of the node, you've created a new, replacement stylesheet object:
const style = document.createElement('style')
document.head.appendChild(style)
const sheet = style.sheet
sheet.ownerNode.textContent = 'div { color: red }'
console.log(style.sheet === sheet); // <===== false!
console.log(style.sheet.ownerNode === style); // <===== true
The old one isn't in the DOM anymore, so it doesn't have an ownerNode
.