querySelectorAll() the best JavaScript function in the world!

Can querySelectorAll() be used to select elements in iframes or shadow DOM?

1 answer

  1. `querySelectorAll()` can be used to select elements within iframes or shadow DOM, but you need to access those elements' documents explicitly.

    For iframes, you'll need to access the contentDocument or contentWindow.document of the iframe element to use `querySelectorAll()`:

    ```javascript
    const iframe = document.querySelector('iframe');
    const iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
    const iframeElements = iframeDocument.querySelectorAll('your_selector');
    ```

    For shadow DOM, you'll need to access the shadowRoot of the custom element:

    ```javascript
    const customElement = document.querySelector('your_custom_element');
    const shadowRoot = customElement.shadowRoot;
    const shadowElements = shadowRoot.querySelectorAll('your_selector');
    ```

    Keep in mind that cross-origin policies might restrict the access to the content of an iframe, and you might need to deal with browser compatibility issues when working with shadow DOM.

Related Questions