Is there a way to select an element by innerHTML without using loops? Can it be done using something like
document.querySelector('div[innerHTML="Sometext"]')
or
document.querySelector('div[textcontent="Sometext"]')
I used jq "contains" to achieve this. for example if i want to get anchor tag with some inner Html then i would do something like this
$('a:contains("sometext")')
I've found some solutions here with vanilla js.
const targetTagName = "div";
const targetText = "Sometext";
const element = document.evaluate(`//${targetTagName}[text()="${targetText}"]`, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
const targetClassName = "className";
const targetText = "Sometext";
const element = document.evaluate(`//*[@class="${targetClassName}"][text()="${targetText}"]`,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;
const targetId = "id";
const targetText = "Sometext";
const element = document.evaluate(`//*[@id="${targetId}"][text()="${targetText}"]`,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;
const targetSelection = "div";
const targetText = "Sometext";
const elements = Array.from(document.querySelectorAll(targetSelection)).filter(item => item.innerText == targetText);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With