Skip to content
Advertisement

Get html elements inside shadow root using javascript

I have example HTML code:

<section class="search-module">
    #shadow-root (open)
        <div class="app">
            <div class="title">Product Title</div>
        </div>
</section>

And with this code I can access to shadow root element parent container:

var searchModule = document.getElementsByClassName("search-module").item(0);

But can’t get elements inside shadow root container using this command:

searchModule.getElementsByClassName("title") // undefined

Advertisement

Answer

You have to navigate to shadow-root first then you can get it:

const searchModule = document.querySelector('.search-module');
const searchModuleRoot = searchModule && searchModule.shadowRoot;

const title = searchModuleRoot.querySelector('.title');
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement