Get html elements inside shadow root using javascript

Tags: , , ,

I have example HTML code:

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

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


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

Source: stackoverflow