Search code examples
htmlcssgoogle-chromedominnerhtml

Chrome extension: Add style to element if it contains particular text


I want to add styling to an element only if it contains a particular string. i.e. if(el contains str) {el:style}.

If I wanted just the links containing w3.org to be pink, how would I find <a href="http://www.w3.org/1999/xhtml">article < /a> inside the innerHTML and then style the word "article" on the page.

So far, I can turn ALL the links pink but I can't selectively target the ones containing "www.w3.org".

var links = [...document.body.getElementsByTagName("a")];
for (var i = 0; i < links.length; i++) {
  links[i].style["color"] = "#FF00FF";
}

How would I apply this ONLY to the elements containing the string "w3.org"?

I thought this would be so simple at first! Any and all help is appreciated.


Solution

  • While you can't filter by non-exact href values when finding the initial list, and you can't filter by contained text then either, you can filter the list after the fact using plain javascript:

    var links = [...document.body.getElementsByTagName("a")];
    for (var i = 0; i < links.length; i++) {
      if (links[i]['href'].indexOf('www.w3.org') == -1) { continue };
      links[i].style["color"] = "#FF00FF";
    }
    

    Assuming you want to filter by the href, that is. If you mean the literal text, you would use links[i]['text'] instead.