2

I am trying to run the following block of code on https://lichess.org/uZIjh0SXxnt5.

var x = document.getElementsByTagName("a");

for(var i = 0; i < x.length; i++) {
    if(x[i].href.includes("WaisKamal") && x[i].classList.contains("user_link")) {
        x[i].innerHTML = '<span class="title" data-title="GM" title="Grandmaster">GM</span> ' + x[i].innerHTML;
    }

    if(x[i].href.includes("WaisKamal") && x[i].classList.contains("text")) {
        x[i].innerHTML = '<span class="title" data-title="GM" title="Grandmaster">GM</span> ' + x[i].innerHTML;
        console.log(x[i]);
    }
}

I am using tampermonkey to automate the process. When the page loads, the first if statement runs correctly, but not the second one. However, when I run the second one from the browser console, it works fine.

Here is what the script does in more detail (I want to add those orange "GM"s):

Without the script

enter image description here

With the script

enter image description here

What I want

enter image description here

I have checked this but it didn't solve my problem.

Any help? Thanks in advance.

Vasan
  • 4,810
  • 4
  • 20
  • 39

1 Answers1

4

Most of that page is loaded dynamically (AJAX-driven), which means that your script will normally finish running long before the nodes, that you are interested in, appear in/on the page.

You must use AJAX-aware techniques such as waitForKeyElements or MutationObserver.

Here's a complete Tampermonkey script that illustrates the process:

// ==UserScript==
// @name     _Lichess.org, Glorify select users
// @match    *://lichess.org/*
// @require  https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// @grant    GM.getValue
// ==/UserScript==
//- The @grant directives are needed to restore the proper sandbox.

waitForKeyElements ("a[href*='WaisKamal']", spiffifyLink);

function spiffifyLink (jNode) {
    var oldHtml = jNode.html ();
    var newHtml = '<span class="title" data-title="GM" title="Grandmaster">GM</span> ' + oldHtml;
    jNode.html (newHtml);
}

See this other answer for more information about choosing and using waitForKeyElements and/with jQuery selectors.

Brock Adams
  • 90,639
  • 22
  • 233
  • 295