简体   繁体   中英

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.

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")}`);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM