Why is StyleSheet's ownerNode null after insertion?

402 Views Asked by At

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')

1

There are 1 best solutions below

0
On BEST ANSWER

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.