skip to Main Content

I’m working on a custom user script that will block/mark users from my list. Say the list will contain strings "EvilJoe", "ToxicWill" & "NegativeSara". I want to find all, say, "span.username" elements where text inside the span contains one of the strings above, so for example "User EvilJoe Premium" would match.

I can do it with a loop through badUserNames, where for each badUserNameI’d do something like

 $("span.username:contains(badUserName)").append(" - bad guy");

Is this an effective solution though?

2

Answers


  1. :contains will be slow if there is a large number of DOM elements because the jQuery itself acting as a middle to translate the :contains to a native JS function. in that case it is better to use a regular expression like this:

    var badUserRegex = new RegExp('(EvilJoe|ToxicWill|NegativeSara)', 'i');
    
    // Find all the span.username elements that match the regex
    $('span.username').filter(function() {
      return badUserRegex.test($(this).text());
    }).append(' - bad guy');
    
    Login or Signup to reply.
  2. This code searches the entire body of the page for elements that contain any of the search terms in the searchTerms array. The :not(script) selector is used to exclude any script elements from the search.

    Try below Code

    var searchTerms = ["badUserName"];
    var matchingElements = $("body :not(script)").filter(function () {
      var elementText = $(this).clone().children().remove().end().text();
      return searchTerms.some(function (term) {
        return elementText.indexOf(term) > -1;
      });
    });
    matchingElements.append(" - bad guy");
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <body>
      <div>
        <p>Text content badUserName.</p>
      </div>
      <div>
        <p>Text content badUserName between</p>
      </div>
      <div>
        <p>badUserName text at starts.</p>
      </div>
      <div>
        <p>no text.</p>
      </div>
    </body>

    You can modify this code as per you want

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