SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Apr 2007
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Get href of last <a> tag in a div

    Hi

    i want to get the href of the last <a> tag contained in a div and send the browser there.

    i know how to get how many <a> tags there are but i don't know how to use this to get to the last <a> tag and get the href and send the browser there.

    heres the code i have so far, please help or poinit me in the right direction.

    <div id="LinkBack">
    <a href="link1">link1</a>
    <a href="link2">link2</a>
    <a href="link3">link2</a>
    <a href="link4">link2</a>
    <!--More links go here as this is dynamically created could be 1 linkk could be 100!-->
    </div>
    <a href="#" onclick="BackBut()" title="Continue Shopping" id="Backto"><img src="http://espimages.biz/2132/images/objects/go-shopping.gif" alt="Continue Shopping" class="Basket-Button-Option" /></a>


    <script>
    function BackBut(){
    var thisOne = document.getElementById("LinkBack");
    var items = thisOne.getElementsByTagName("a");
    var Amount = items.length;


    }
    </script>

  2. #2
    SitePoint Enthusiast
    Join Date
    Dec 2007
    Posts
    66
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Keep in mind, your pseudo "back" link is going to be broken for those without JavaScript enabled. A better solution would be to have your server side code create the 'back' link to match whatever the last link was in your div.

    But to answer your question:
    Code:
    <script>
    function BackBut() {
        var thisOne = document.getElementById("LinkBack");
        var items = thisOne.getElementsByTagName("a");
        var lastLink = items[items.length - 1];
        location.href = lastLink.href;
    }
    </script>
    Note, that code is not doing any error checking, so if LinkBack doesn't exist, or if there are no "a" links, then there will be a messy JavaScript error.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •