simonw16
simonw16

Reputation: 1000

Puppeteer. Cannot get node property in evaluate()

How does one find a nondescript radio button element and click it in puppeteer?

I have seen a lot of articles saying, "just use evaluate() and then click it" or similar, and that just doesn't work in my scenario.

Here is what I have:

page.on('console', consoleObj => console.log(consoleObj.text()));

await page.evaluate(() => {
    let container = document.getElementById('container');
    let options = container.getElementsByClassName('labels');

    // OPTIONS GIVES ME AN ARRAY OF JSHandle@node.

    if (options.length > 0) {
        for (let radio of options) {
            let value = radio.value;
            console.log(value);
        }
    }
});

I have no idea what to do. value is always empty.

I need to know its value in order to know whether to click it or not. I intend to pass in a variable to evaluate and then click the right one based on that variable.

If I simply put radio.click() in the for loop, it works in that it clicks each one of the elements and always ends on the last one being selected. So I know click() works. How do I determine WHICH one to click, and choose it?

Here are the 2 radio button elements as HTML:

<input name="choice" value="accept" class="checkbox" type="radio">

<input name="choice" value="reject" class="checkbox" type="radio">

Upvotes: 0

Views: 509

Answers (1)

Ben Richards
Ben Richards

Reputation: 3575

Why not use getElementsByName?

page.on('console', consoleObj => console.log(consoleObj.text()));

await page.evaluate(() => {
    let options = container.getElementsByName('choice');

    if (options.length > 0) {
        for (let radio of options) {
            let value = radio.value;
            console.log(value);
        }
    }
});

Upvotes: 1

Related Questions