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

2

5

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.

Grandpa answered 8/3, 2019 at 17:10 Comment(2)
Sir, is it possible to copy/paste the html dom to actually understand the question ?Noontide
I can't paste the image. I thought I did but it isn't appearing. Let me try to quickly fix thisGrandpa
M
4

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")}`);
Memo answered 8/3, 2019 at 21:38 Comment(0)
L
3

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
Lepton answered 8/3, 2019 at 19:50 Comment(1)
this is also a solution but I am looking for TestCafe solution which I found more convenient.Grandpa

© 2022 - 2024 — McMap. All rights reserved.