Search code examples
javascripthtmlfirefoxgreasemonkey

Change an element of a website using a script?


OBSERVED BEHAVIOR

I am using a website that displays a location on the page.

Example: San Francisco, CA \ Orlando, FL \ etc.

Like the text in the above example the location is static and does not do anything.

Static Location Text

<span class="userinfo2015-basics-asl-location">Orlando, FL</span>

To bring more life to the page and add functionality to that location, I installed GreaseMonkey which allows a user to create scripts that modifies the functionality of a page. Unfortunately the script was outdated and didn't work. But the code seems to be on the right track.

var locE = document.getElementById('span.userinfo2015-basic-asl-location');
var location = locE.textContent;

var newSrc = "https://www.google.com/maps/place/"+location;
var link = document.createElement('a');
link.setAttribute("href",newSrc);
link.setAttribute("target","_blank");
link.innerHTML = location;
locE.parentNode.replaceChild(link,locE);

EXPECTED BEHAVIOR

The GreaseMonkey script would make the static location that you saw above into a link that redirects you to Google Maps.

RELEVANT INFORMATION

Using Greasemonkey Version 3.8

Using FireFox Version 47.0


Solution

  • It should work with a few changes:

    1. It looks like you misspelled your class name.
    2. You need to use getElementsByClassName()[0] to get an element by class name.

    I had some trouble getting this to work in the snippet, but I got it to work in JSFiddle:

    JSFiddle: Span to Link

    Here's the modified JavaScript:

    var locE = document.getElementsByClassName('userinfo2015-basics-asl-location')[0];
    var location = locE.textContent;
    
    var newSrc = "https://www.google.com/maps/place/" + location;
    var link = document.createElement('a');
    link.setAttribute("href", newSrc);
    link.setAttribute("target", "_blank");
    link.innerHTML = location;
    locE.parentNode.replaceChild(link, locE);