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>
</div>
Then I get the jquery image path for each image:
var download_image = jQuery('#download_image');
var images = download_image.find('img');
download_images.each(function(){
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
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
.
source to share
$('.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.
source to share