Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting Elements By InnerHTML with querySelector

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"]')
like image 456
Rahat Saini Avatar asked Aug 12 '26 06:08

Rahat Saini


2 Answers

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")')
like image 136
Rahat Saini Avatar answered Aug 14 '26 20:08

Rahat Saini


I've found some solutions here with vanilla js.

With XPath

By tagName & innerText

const targetTagName = "div";
const targetText = "Sometext";

const element = document.evaluate(`//${targetTagName}[text()="${targetText}"]`, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

Or by ClassName

const targetClassName = "className";
const targetText = "Sometext";

const element = document.evaluate(`//*[@class="${targetClassName}"][text()="${targetText}"]`,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;

Or by Id

const targetId = "id";
const targetText = "Sometext";

const element = document.evaluate(`//*[@id="${targetId}"][text()="${targetText}"]`,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;

With querySelectorAll & filter

const targetSelection = "div";
const targetText = "Sometext";

const elements = Array.from(document.querySelectorAll(targetSelection)).filter(item => item.innerText == targetText);
like image 28
MaelkMark Avatar answered Aug 14 '26 19:08

MaelkMark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!