Reputation:
I need to check a div to see if it contains an 'a' (link). I've been looking at similar questions here, but none seem to do exactly what I'm trying.
Example markup:
<div if='description>
blablablabla
blablablabla
blablablabla
</div>
<div id='description'>
blablablabla
<a href="thelink">The link</a>
blablablabla
</div>
<div id='description>
blablablabla
blablablabla
blablablabla
</div>
The ids are duplicated, and there's nothing I can do about that. However, using .eq() in these cases seems to work fine.
What I need to do, is to check, for instance, cy.get('#description').eq(0) to see if there is an 'a' within it, and click it if there is. If there is no 'a', do nothing.
I've tried things like this, without success:
if (cy.get('#description').eq(0).contains('a')) {
cy.get('#description').eq(0).within( () => {
cy.get('a').click();
});
Probably incorrect code anyway, with regards to the use of within.
This, too:
if (cy.get('#description').eq(0).children().contains('a')) {
cy.get('#description').eq(0).within( () => {
cy.get('a').click();
});
All help and/or hints are, as allways, appreciated. (Man, I miss Selenium sometimes, where I could use Java or Kotlin code with near full freedom.)
Upvotes: 4
Views: 4528
Reputation: 18650
You can use children for this as mentioned by @lbsn and then add click()
.
cy.get('#description').eq(0).children('a').click()
You can also look into this, like when you get the a
then click on it and exit each()
and if there is no child element, the test continues and doesn't fail.
cy.get('div#description').each(($ele) => {
if ($ele.children('a').length > 0) {
cy.wrap($ele).children('a').click()
return false //Remove if you want to continue the loop even after finding the child element
}
})
Upvotes: 3