Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Regular Coder
    Join Date
    Jun 2002
    Posts
    553
    Thanks
    0
    Thanked 0 Times in 0 Posts

    jquery - how to get This one in each loop?

    In the code below I am simply trying to retrieve the hyperlink from each li of class 'first-item' within some complex html (that I am stuck with). As the code is written, I retrieve the first url, http://somesite1/1, both times. What selector or other structure do I need to get each one as I iterate through the each function? - G

    <script>

    $(document).ready(function() {


    $("#cb li.ct").each(function()
    {

    var link = $('li.first-item a').attr('href');
    alert(link);

    });

    });
    </script>

    <div id="cb">
    <ul class="cb-list">
    <li class="ct">
    <span>first</span>
    <div class="ct-more">
    <ul class="ct-lnk">
    <li class="first-item"><a href="http://somesite1/1" >link11</a></li>
    <li><a href="http://somesite1/2" >lin12</a></li></div> </li>
    <li class="ct">
    <span>second</span>
    <div class="ct-more">
    <ul class="ct-lnk">
    <li class="first-item"><a href="http://somesite2/1" >link21</a></li>
    <li><a href="http://somesite2/2" >link22</a></li></ul></div>
    </li></ul>
    </div>

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,391
    Thanks
    11
    Thanked 568 Times in 561 Posts
    Why not just use this
    Code:
    $("li.first-item a").each(function()
    {
    
    var link = $(this).attr('href');
    alert(link);
    
    });
    If you really need to come to the <a> from the li.ct then you can use this:
    Code:
    $("#cb li.ct").each(function() {
       var link = $(this).find('li.first-item a').attr('href');
       alert(link);
    });

  • #3
    Regular Coder
    Join Date
    Jun 2002
    Posts
    553
    Thanks
    0
    Thanked 0 Times in 0 Posts
    ah, nice - thanks very much, devnull69!

  • #4
    The fat guy next door VIPStephan's Avatar
    Join Date
    Jan 2006
    Location
    Halle (Saale), Germany
    Posts
    8,607
    Thanks
    6
    Thanked 997 Times in 970 Posts
    And validate your HTML. You have an unclosed ul there. Things like that can influence the outcome since DOM traversal might screw up.


  •  

    Posting Permissions

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