Reputation: 425
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>
Upvotes: 14
Views: 15964
Reputation: 141
const parent_node = await child_node.getProperty('parentNode')
You can try this one
Upvotes: 10
Reputation: 25280
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();
Upvotes: 8