Search code examples
javascriptjqueryselectionhrefattr

jQuery select href values in nested divds


Although I found several answers to select a href attribute neither of them is working for me. Maybe someone can help.

The html is as follows

<div class="galleryitem">
   <div class="itemlink">
      <a href="page1.html">Page</a>                 
   </div>
   <div class="itemimg">
      <a href="img/test1.png">test1.png</a>                 
   </div>
</div>

<div class="galleryitem">       
   <div class="itemlink">
    <a href="page1.html">Page 1</a>                 
   </div>
   <div class="itemimg">
      <a href="img/test2.png">test2.png</a>                 
   </div>
</div>

Now i want to geht all the attribute values in the hrefs and tried with

$('.galleryitem').each(function() {

   var link = $(this).children('itemlink a').attr('href');
   var img = $(this).children(".itemimg a").attr("href");       

   //jQuery("#somediv").append("<a href='" + link + "'><img class='cloudcarousel' src='" + img + "'/></a>");

});

I dont know why link and img are undefined. Even $(this).children('.itemlink a') is undefined.

Can anyone help on this?


Solution

  • Try with find

    $('.galleryitem').each(function() {
        var link = $(this).find('itemlink a').attr('href');
        var img = $(this).find(".itemimg a").attr("href"); 
        //...
    })