1

My school website has homework download links and I want to distinguish them by coloring them different colors.
EG: Microsoft Word files would be blue and .RTF files would be green.
Since I'm new to this none of my scripts are working.

My script:

// ==UserScript==
// @name         Homework Help
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Color links for different file extensions
// @author       You
// @match        (My School Website)
// @grant        none
// ==/UserScript==

function getFileExtension(filename) {
    return filename.split('.').pop();
}

(function() {
    'use strict';

    // Your code here...
    var links = document.getElementByTagName("a");
    var element;

    for (var i = 0; i < links.lenth(); i++){

        element = rtfs[i];

        if( getFileExtension(element.href) == "rtf" ){
            element.style.color = "green";
        }
    }
})();

I tried googling it but found no solution.

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
  • 1
    Typo: `getElementByTagName` should be `getElementsByTagName`. You can detect such simple bugs by using the built-in devtools debugger: add `debugger;` line somewhere inside the code, for example after `'use strict';`, open devtools (F12), reload the page, the debugger will pop up, so you can step through the code and inspect the values. – wOxxOm Oct 23 '16 at 00:27

1 Answers1

0
  1. Your school's website may well load the file list using AJAX. If that is the case, you need to use AJAX-aware techniques.
  2. Also, as pointed out by wOxxOm, there is a syntax error in the code.
  3. Occasionally, depending on the site's CSS you may need to use the !important flag.

The following complete script uses jQuery and waitForKeyElements() to address items 1 & 2 (it works on static pages too):

// ==UserScript==
// @name     _Color code links by file extension
// @match    http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
//- The @grant directive is needed to restore the proper sandbox.

// PICK A MORE PRECISE SELECTOR IF YOU CAN.
waitForKeyElements ("a", colorLink);

function colorLink (jNode) {
    var fileHref        = jNode.attr ("href");
    if ( ! fileHref)    return; //-- Not every link has an href.

    var fileExt         = fileHref.split ('.').pop ().toLowerCase ();
    switch (fileExt) {
        case "rtf":
            jNode.css ("color", "green");
        break;
        case "doc":
            jNode.css ("color", "pink");
        break;
        default:
            //-- No action needed.
        break;
    }
}

Note: The jQuery selector "a" will filter through every link! But we need page details to pick a more targeted selector. Use the techniques shown at this question, to narrow the selection.

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