<a href="test1.php" class="test">test1.php</a>
<a href="test2.php" class="test">test2.php</a>
<a href="test3.php" class="test">test3.php</a>
<a href="test4.php" class="test">test4.php</a>
...
<a href="testN.php" class="test">testN.php</a>
We can get attr a one link:
$('.el').click(function(){
var href = $('.test').attr('href');
});
But how get array with all href all links?
asked Jul 22, 2014 at 13:39
user2881809
3 Answers 3
Try to use .map() along with .get() to collect all of those href associated with relevant anchor tags in an array,
$('.el').click(function(){
var href = $('.test').map(function(){
return $(this).attr('href');
}).get();
});
answered Jul 22, 2014 at 13:40
Balachandran
9,6271 gold badge19 silver badges26 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You can do that with $.map
$('.el').click(function(){
var hrefArray = $.map($('.test'), function(el) { return $(el).attr('href'); });
});
answered Jul 22, 2014 at 13:40
adeneo
319k29 gold badges410 silver badges392 bronze badges
4 Comments
Frédéric Hamidi
Since you're projecting from a jQuery object, you could as well call
$(".test").map(...).get().adeneo
@FrédéricHamidi - that's true, but
$(collection).map() creates a new collection wrapped in jQuery that I then have to unwrap with get(). As I'm creating an array, I'm using $.map instead as it will create the array directly without wrapping it in jQuery and then needing to be unwrapped again. This is why there are two methods with different use cases.Frédéric Hamidi
I see your point. You're indeed saving a call to
Array.slice(), which may come in handy if $(".test") matches a lot of objects.adeneo
Indeed,
get() just calls Array.slice, and it also saves the work it takes for jQuery to wrap it in the first place etc.var hrefArray = [];
$.each($('a'), function(index, element){
hrefArray.push(element.href);
});
answered Jul 22, 2014 at 13:40
Rob Schmuecker
8,9642 gold badges21 silver badges34 bronze badges
Comments
lang-js