Home > Blockchain >  How to get children of HTML custom elements?
How to get children of HTML custom elements?

Time:10-07

I'm writing a scraper with puppeteer and I need to fill the fields of a form built with Aura js. The problem is I'm not able to reach the input and password fields because they're inside a custom element:

<lightning-input class="input sfdc_usernameinput slds-form-element" data-aura-rendered-by="116:0" lightning-input_input-host=""><span lightning-input_input="" data-aria="" class="slds-assistive-text"></span><label lightning-input_input="" for="input-5" class="slds-form-element__label slds-no-flex slds-assistive-text">Username</label>
    <div lightning-input_input="" class="slds-form-element__control slds-grow">
        <input lightning-input_input="" type="text" id="input-5" aria-invalid="false" placeholder="Username" class="slds-input">
    </div>
</lightning-input>

And when I try:

await page.type('#input-5', 'myusername');

it throws the error:

Error: No node found for selector: #input-5

This is confirmed if I try document.getElementById('#input-5') in browser console.

So how do I get that input?

EDIT: Adding a screenshot that shows what happens here: the markup with children elements but no way to access to them.

custom element lightning-input with some debug

CodePudding user response:

The element you're looking for are encapsulated in the shadow DOM thus making them hidden from the normal DOM query methods.

You can still query them like this:

document.querySelector("lightning-badge").shadowRoot.querySelector('#input-5')

Example: on this Aura demo page I can get text of a lightning badge with this code:

document.querySelector("lightning-badge").shadowRoot.textContent

"Start Position"

This query can of course can be executed in a page.evaluate method with puppeteer as well.

  • Related