I'm trying to click on one value (odds) based on the name of the other element but those two need to be inside a specific parent element which I get by the text inside it.
The snippet below can be found multiple times on the same page with the same classes so targeting by class is not an option.
I first need to get a container with text "1st Goal. Then I need to get it's parent and in the parent, I need to get the second div element (class parent2). That element holds other elements. Let's imagine I need to get the element of value 200 and click on it.
I've tried using parentElement, parentNode but always get the 'undefiend' when getting a parent of the child element, although the child element is retrieved successfully. I just can't get the parent from where I could go down the tree to the desired element and click on it.
<div class="group ">
<div class="parent1 "><span>1st Goal</span></div>
<div class="parent2">
<div class="container ">
<div">
<div><span>Malaga</span><span class="odds">200</span></div>
<div><span>No 1st Goal</span><span class="odds">300</span></div>
<div><span>Las Palmas</span><span class="gll-odds">400</span></div>
</div>
</div>
</div>
<div></div>
</div>
Java Prime Pack We can get element text in Puppeteer. This is done with the help of the textContent property. This property of the element is passed as a parameter to the getProperty method.
The read-only parentNode property of the Node interface returns the parent of the specified node in the DOM tree. Document and DocumentFragment nodes can never have a parent, so parentNode will always return null . It also returns null if the node has just been created and is not yet attached to the tree.
If you are okay with using XPath expression, you can use the following statement:
//div[contains(@class, "group") and contains(., "1st Goal")]/div[@class="parent2"]//span[@class="odds"]
This XPath expression queries for a div
element having the class group
and containing the text 1st Goal somewhere. Then it will query the children div
with the class parent2
and query span
elements with class odds
inside.
To get the element with puppeteer, use the page.$x
function. To click the element, use elementHandle.click
.
Putting all together, the code looks like this:
const [targetElement] = await page.$x('//div[contains(@class, "group") and contains(., "1st Goal")]/div[@class="parent2"]//span[@class="odds"]');
await targetElement.click();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With