Search code examples
javascripthtmlcss-selectorsselectors-api

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


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.


Solution

  • 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>