JQuery: get link by class or selector

I create a list of images from a folder and then I open them in fancybox ... so I have streams, large images and a text link to the full image.

<div id="download_image">
  <p><a href="images/download/folder/big/<?php echo $file;?>" class="fancybox"><img src="<?php echo $path;?><?php echo $file?>" /></a></p>
  <p><a href="images/download/folder/full/<?php echo $file;?>.zip" class="btn-download">DOWNLOAD</a></p>


Then I get the jquery image path for each image:

var download_image = jQuery('#download_image');
var images  = download_image.find('img');

    var img = jQuery(this);
    var img_source = img.attr('src');


Now I need to get the url of the "btn-download" link for each image ... but I don't know which selector I should be using! Any advice?


source to share

5 answers

Use $('.btn-download')

to select an element by class.

If you want to get the href attribute, just use:

var href = $('.btn-download').attr('href');


To cycle through each item use:

    var href = $(this).attr('href');
    // do something with href




try it





var download_image = jQuery('#download_image');

download_image.each(function() {
    var imgUrl = $(this).find('p > a > img').prop('src');
    var downloadUrl = $(this).find('p > a.btn-download').prop('href');
    // do something with the urls here.



The function each

is overkill because you only have to have one element with a specific ID. Listed here just in case you want to have more than one downloadable image and button.

In your question, you indicate that you are getting the path for each image. I highly recommend that you make a download_image

class if you have more than one element download_image




$('.btn-download').each(function() {
  console.log(this.href); // get the normalized `href` property; fastest solution
  console.log($(this).attr('href')); // get the exact `href` attribute value


Note that the answers protecting $('.btn-download').attr('href')

are incorrect as they return the attribute value href

for the first element in the set.



Try the following:

    var img_source = $('img', this).attr('src');
    var link_href = $('a.btn-download', this).attr('href');




All Articles