2

Whenever I try to use document.getElementById inside a shadow dom script tag, I always get null I looked at questions here and here, but none of the answers helped.

Right now I'm using this script, but I'm pretty sure that there's a better way to do this.

window.document.body.getElementsByClassName('calculator')[0].getElementsByClassName('content')[0].shadowRoot.getElementById('test')
user12976477
  • 57
  • 1
  • 7
  • Actually no, this is the whole purpose of a shadow DOM. It isolates the elements inside it from the real DOM so that selectors of the parent DOM won't return elements inside the shadow DOM. This applies to CSS and JavaScript. – Guerric P Mar 19 '20 at 20:33

1 Answers1

4

This is how you use selectors inside a shadow DOM. You have to find the shadowRoot first, then call getElementById from it.

customElements.define("with-shadowroot", class extends HTMLElement {  
    constructor() {
        super()
          .attachShadow({ mode: 'open' })
          .innerHTML = `<div><div id="some-div">I'm inside shadowDOM!</div></div>`;
    }
});

console.log(document.getElementById('some-div'));

const divs = document.getElementsByTagName('with-shadowroot');
console.log(divs[0].shadowRoot.getElementById('some-div'));
<with-shadowroot></with-shadowroot>
Guerric P
  • 30,447
  • 6
  • 48
  • 86