1
<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?

3 Answers 3

2

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();
});
Sign up to request clarification or add additional context in comments.

Comments

2

You can do that with $.map

$('.el').click(function(){
    var hrefArray = $.map($('.test'), function(el) { return $(el).attr('href'); });
});

4 Comments

Since you're projecting from a jQuery object, you could as well call $(".test").map(...).get().
@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.
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.
Indeed, get() just calls Array.slice, and it also saves the work it takes for jQuery to wrap it in the first place etc.
0
var hrefArray = [];
$.each($('a'), function(index, element){
    hrefArray.push(element.href);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.