Search code examples
javascripthrefhttp-redirectuserscripts

Find the first link with given tag and open it (userscript)


This seems a simple problem, still I cannot manage to find out how to solve it.

I'd like to write a greasemonkey userscript for a webshop what is doing the next when I open their site (what is basically a listing of items under each other).

  • checking if there is any new items since my last visit (in the html of the site there will be a "new " mark in their class) in case it finds 1 or more items with the new tag, go to the next step (else do nothing)

  • redirect this main page to the first link with the "new " tag

So when I open http://mywebsite.com/ I should be redirected immediately to http://mywebsite.com/forsale/100009/ in this example. But I don't know what will be the url, that's why a script needs to check the links. Only the first match I need (new items are always on top). Not old (without the new tag) and not new items under/after the first one.

This is how the website's source looks:

<div class="item new "  id="item_0" style="">
  <div class="item_click_overlay">
    <a href="http://mywebsite.com/forsale/100009/">
    <img src="http://mywebsite.com/pics/100009.gif">
    </a>
  </div>
</div>

<div class="item new "  id="item_1" style="">
  <div class="item_click_overlay">
    <a href="http://mywebsite.com/forsale/100007/">
    <img src="http://mywebsite.com/pics/100007.gif">
    </a>
  </div>
</div>

<div class="item  "  id="item_2" style="">
  <div class="item_click_overlay">
    <a href="http://mywebsite.com/forsale/100006/">
    <img src="http://mywebsite.com/pics/100006.gif">
    </a>
  </div>
</div>

<div class="item  "  id="item_3" style="">
  <div class="item_click_overlay">
    <a href="http://mywebsite.com/forsale/100002/">
    <img src="http://mywebsite.com/pics/100002.gif">
    </a>
  </div>
</div>

Solution

  • Something like this you mean?

    var newLink = $( ".item.new:first" ).find('a:first').attr('href');
    window.location.replace(newLink);
    

    Or this without jQuery:

    var newLink = document.getElementsByClassName('item new')[0].getElementsByTagName('a')[0].href;
    window.location.replace(newLink);