skip to Main Content

This is my first post after lurking for years, so please excuse me if the formatting of this post is incorrect. I am currently modifying a Tampermonkey script (Firefox) that searches a webpage for a specific set of text strings (which I have predefined in the script) and highlights the text on the page once it loads. That part of the script works fine, however, now I am trying to change the background color of one of the parents.

I would like to change the background color for the entire element (div class "shop-item") that contains the text "Item Name":

<div class="shop-item">
  <div class="item-img" tabindex="0" style="background-image:url("URL_HERE");" border='1'>
  </div>
  <p class='item-name'>
    <b>Item Name</b>
  </p>
</div>

The entire script works flawlessly, but now that I am trying to highlight additional items other than the text string, I am running into issues. This is the part of the script I’m having trouble with:

    var textnodes = document.evaluate("//body//text()", document, null,
        XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);

    for (var i = 0; i < textnodes.snapshotLength; i++) {
    var node = textnodes.snapshotItem(i);

        if (!(node.data.match(/^s*$/))) {
        var s = " " + node.data + " ";
        changes = 0;
        var d = highlight(quoteHTML(s));
        if (changes > 0) {
            var rep = document.createElement("span");
            rep.innerHTML = d.substring(1, d.length - 1);
            node.parentNode.replaceChild(rep, node);
            node.closest("div").backgroundcolor("#1AFF00FF");
        }
        }
    }
    }

The issue lies with the last line of code:
node.closest("div").backgroundcolor("#1AFF00FF");

I’ve tried a bunch of other combinations including .parentNode, but haven’t been successful. I’m fairly new to Javascript/Tampermonkey scrpts, so any help would be much appreciated!

2

Answers


  1. Chosen as BEST ANSWER

    Thanks for everyone's input. With the suggestions provided, I wasn't able to get exactly what I was looking for, but it lead me in the right direction. Replacing the last line with the following worked:

    node.parentElement.closest(".shop-item").style.backgroundColor = "#1AFF00FF";
    

  2. You need to change it to this:

    node.closest("div").style.backgroundColor = "#1AFF00FF";
    

    Reference: Style backgroundColor Property

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search