How to select all anchor tags with specific text content with Javascript?

Nagarjun Prasad picture Nagarjun Prasad · Jan 24, 2018 · Viewed 8k times · Source

I want to use the selector in document.querySelector() to select all a tags with the text "print".

<a href="https://www.google.co.in">print</a>

how can I select the same. I don't want to use jQuery. I doesn't have to be querySelector only but any other selector will do.

Answer

Ele picture Ele · Jan 24, 2018

var findElements = function(tag, text) {
  var elements = document.getElementsByTagName(tag);
  var found = [];
  for (var i = 0; i < elements.length; i++) {
    if (elements[i].innerHTML === text) {
      found.push(elements[i]);
    }
  }
  
  return found;
}

console.log(findElements('a', 'print'));
<a href="https://www.google.co.in">print</a>
<a href="https://www.google.co.in">skip</a>