Reputation: 2303
This is something I really should have learned long ago, but I somehow never did.
var productDivs = $('#HomeNewProducts .ProductList li');
So here is a simple line that selects multiple li's and its children. Now, let's say I want to extract a link from each of these elements to use it after to link an element I'm appending.
var link = $('#HomeNewProducts .ProductList li .ProductDetails a').attr('href');
productDivs.append('<a href=\"' . link . '\"><img src="#" /></a> ' );
Upvotes: 1
Views: 112
Reputation: 102763
map
is good for extracting a collection of properties from a collection:
// get .`attr('href')` from each element
var links = $('#HomeNewProducts .ProductList li .ProductDetails a');
var hrefs = links.map(function(link) {
return $(link).attr("href");
});
But since it looks like you want to iterate over a set of elements, and append something to each, I guess you want JQuery's each
:
$('#HomeNewProducts .ProductList li').each(function(index, element) {
// find child link of the current element
var link = $(element).find(".ProductDetails a").attr('href');
// append to the current element
$(element).append('<a href=\"' . link . '\"><img src="#" /></a> ' );
});
Here's a simplified Fiddle of the general idea.
Upvotes: 2
Reputation: 196002
Since you have already cached the li
elements in productDivs
us it when searching for further descendants.
Then use .each()
to iterate over a group of selected elements
var productDivs = $('#HomeNewProducts .ProductList li');
var link = productDivs.find('.ProductDetails a').each(function(){
// do the appending from here
// this.href refers to the current link
productDivs.append('<a href=\"' + this.href + '\"><img src="#" /></a>' );
});
Upvotes: 0
Reputation: 769
Try this:
var link = $('#HomeNewProducts .ProductList li .ProductDetails a').attr('href');
productDivs.append('<a href=\"' + link + '\"><img src="#" /></a> ' );
The plus signs should properly insert the link
variable into the string.
Upvotes: 4