如何从selectorAll过滤后获得选择器?



我想从nodelist获得选择器,用于特定的过滤,传递给puppeteer waitForSelector,需要css选择器。我想是因为苹果是老二。我期望得到button:nth-child(2)

const fruits = document.querySelectorAll('button');
for (const fruit of fruits) {
if (fruit.textContent == 'Apple') {
// get the element handle and pass to waitForSelector
console.log('Apple')
}
}
<button type="button">Orange</button>
<button type="button">Apple</button>

根据andy的建议,我是这样解决的。感谢andy

const fruits = document.querySelectorAll('button');
for (const fruit of fruits) {
if (fruit.textContent == 'Apple') {
fruit.setAttribute('data-type', 'Apple');
break
}
}
return document.querySelector('button[data-type=Apple]')
<button type="button">Orange</button>
<button type="button">Apple</button>

最新更新