Psdet
Psdet

Reputation: 689

Select a child element from a parent using a cousin node of the same parent

I'm using TestCafe Selectors to select elements. This is a complex nested scenario of cousin child.

Here is the HTML to get an idea of what I mentioned above:

html

In the picture, I have mentioned 1 and 2 which are the parent element (has same DOM) who has a grand grand child path and the same parent's grand grand child in the other tree is <span title='John' /span>. I need the node of the path but need to link <span title='John' /span> because all the parents have the same DOM.

I don't know how to resolve this situation using TestCafe. Do I have to use jQuery? If yes, then how? I tried a lot but couldn't figure out.

Upvotes: 5

Views: 1640

Answers (2)

omikes
omikes

Reputation: 8513

In jQuery you can fetch all the elements with class projects-project-role, and then search each of those elements for a path tag and an element of the class person-name, and add their values to an array, like this:

var namePath = []; // initialize empty name/path array
$(".projects-project-role").each(function() {  // go through each element of class projects-project-role
    var path = $(this).find("path").attr("d"); // look for a path tag subelement and grab its d attribute
    var name = $(this).find(".person-name").text(); // look for an element of class person-name and grab its text
    namePath.push({path: path, name: name}); // add the gathered path and name to an array
});
console.log(namePath); // display the array

EDIT: Or in shorthand, and with map:

var namePath = $(".projects-project-role").get().map((p)=>({path: $(p).find('path').attr('d'), name: $(p).find('.person-name').text()}));
console.log(namePath); // display the array

Upvotes: 3

hdorgeval
hdorgeval

Reputation: 3030

TestCafe API is smart enough to handle your case:

const JohnSelector = Selector('div.person-identity')
  .find('span.person-name')
  .withExactText('John');

const pathSelector = JohnSelector
  .parent('div.projects-project-role')
  .prevSibling('div.projects-project-role')
  .find('button svg path')
  .nth(1);

console.log(`${await JohnSelector.innerText}`);
console.log(`${await pathSelector.getAttribute("d")}`);

Upvotes: 4

Related Questions