Search code examples
javascripturlhrefuserscriptsgetelementsbyclassname

How can I make a userscript that gets the href attribute contents of every element in a specified class?


This is the html format of the webpage:

<ul id="all_items_container" >
<li class="first item" id="">
    <a class="item title_link" href="#942" title="blah blah" id="" >
        <span class="title" >blah blah</span>
    </a>
</li>
<li class="item " id="">
    <a class="item title_link" href="#846" title="blah blah blah" id="" >
        <span class="title" >blah blah blah</span>
    </a>
</li>
<li class="item " id="">
    <a class="item title_link" href="#745" title="blah blah blah blah" id="" >
        <span class="title" >blah blah blah blah</span>
    </a>
</li>

I need to be able to get all of the href attributes for the elements in the "item title_link" class and then take away the # sign, and then convert it into a url. For example, the first element in the "item title_link" class has an href value of "#942", I need to be able to convert that string into something like this "http://www.domainname.com/index/942/get".

I need to be able to create a script that can do that for all of the elements that are in that class and then navigate to each of the generated links. Here is the script that I have so far that doesn't work:

var itemLinks = document.getElementsByClassName("item title_link");
var itemLinksHRefs = itemLinks.href;
var actualItemHRefs = itemLinksHRefs.replace("#","");
var actualItemLinks = "http://www.domainname.com/index/"+actualItemHRefs+"/get";

window.location.href = actualItemLinks;

I know that my script is probably way off of the right way to do this but I am quite new to creating userscripts, so any help would be greatly appreciated.

EDIT: I need a way to make the script wait to start for 6 seconds, then get the hrefs values for all of the elements in the "item title_link" class and convert them into a list of urls, and then either have the script open all of those links in new tabs or be able to export those links to a text file in this format:

http://www.domainname.com/index/942/get
http://www.domainname.com/index/846/get
http://www.domainname.com/index/745/get

Solution

  • you are trying to set location to multiple links... and not .href, but .getAttribute('href');

    var a,b,c,d, len;
    
    a = document.getElementsByClassName("item title_link");
    len = a.length;
    
    for (var i = 0; i <= len - 1; i++) {
        b = a[i].getAttribute('href');
        c = b.replace("#", "");
        d = "http://www.domainname.com/index/" + c + "/get";
        console.log(d); //just to check them out
    }
    
    //window.location.href = d;
    //or whatever you wanted to do with that...