i've been working on a project with puppeteer and it was going great so far until a tried to localize div's depending on their text. I can't use the div id, name or class, i need to find it by the text inside of it. My idea is to create an array of all the text i need to find and then loop trought the div's to find the ones that match any of the text in the array. Can anybody help me find a solution? Thank you!
This is relatively straightforward using vanilla javascript (no JS libraries):
// Get an array of all <divs>:
let allDivs = [... document.getElementsByTagName('div')];
// Loop through allDivs, checking the text of each one:
allDivs.forEach((div) => {
let textInsideDiv = div.textContent;
// THE REST OF YOUR CODE HERE
// if (myArrayOfText.indexOf(textInsideDiv) > -1)) { etc.}
}
Matching by text isn't something you can do with plain CSS Selectors, but it is supported in jQuery and xPath, if they are possible for you to use.
The jQuery :contains()
selector:
$('div:contains("yourText")')
The xPath text()
selectors
$x('//div[text()="yourText"]') // Match
$x('//div[contains(text(), "yourText")]') // Substring / Contains
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.