Search code examples
javascriptcsscssom

Why is StyleSheet's ownerNode null after insertion?


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


Solution

  • 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.