簡體   English   中英

使用同一父級的表親節點從父級中選擇子元素

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

我正在使用TestCafe選擇器來選擇元素。 這是表親孩子的復雜嵌套場景。

這是HTML,以了解我上面提到的內容:

HTML

在圖片中,我提到了12 ,它們是父元素(具有相同的DOM),具有宏大的子path ,而另一個樹中的同一父母的大祖兒是<span title='John' /span> 我需要path的節點,但需要鏈接<span title='John' /span>因為所有父節點都有相同的DOM。

我不知道如何使用TestCafe解決這種情況。 我必須使用jQuery嗎? 如果是,那怎么樣? 我試了很多但是想不出來。

TestCafe API非常智能,可以處理您的情況:

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

jQuery您可以使用類projects-project-role獲取所有元素,然后在每個元素中搜索path標記和類person-name的元素,並將它們的值添加到數組中,如下所示:

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

編輯:或者用速記,並用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM