Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Element ID by String it Contains using Plain Javascript

Tags:

javascript

How can I get an elemnts ID based on the string it contains?

<span id="th67">This the string I need to match</span>

I can't make use of JQuery or any other Javascript library to do this.

I need to do this for a selenium test.

I didn't realise how useless I am in JS without my libraries!

Thanks all for any help.

like image 844
Kay Avatar asked Dec 03 '22 08:12

Kay


1 Answers

Well, if you know what kind of tag you're looking for, you can just do:

var spans = document.getElementsByTagName('span'), targetId;
for (var i = 0; i < spans.length; ++i) {
  if (spans[i].innerText === stringToMatch) {
    // found it ...
    targetId = spans[i].id;
    break;
  }
}
if (targetId) {
  // ... do whatever ...
}

If you want to get fancy you could construct an xpath query, I guess.

like image 142
Pointy Avatar answered Jan 19 '23 05:01

Pointy