jQuery How to Get All Href Attribute Values From a List
Learn how to get all href attribute values from a list with jQuery
Published
Let’s say we have the following nav bar. What if we need to get all href attribute values from the a element list using jQuery?
<nav>
<a href="www.google.com/home">Home</a>
<a href="www.google.com/findyourcity">Find Your City</a>
<a href="www.google.com/howitwork">How It Works</a>
<a href="www.google.com/faq">FAQ</a>
<nav>
If you wish to process a jQuery array or object use jQuery .map() method.
jQery map Method Syntax
$('div').map( callback );
So, we can write following code to get all href attribute values from the a element list using jQuery
Final Code
var aLinks = $('nav a').map( function() {
return $(this).attr('href');
}).get();
for (i=0; i < aLinks.length; i++) {
console.log (aLinks[i])
}
If we want to get a single href value we can use .attr() method in jQuery. This will only give you the attribute value for the first item found. jquery $('nav a').attr('href');
jQery attr Method Syntax
$('selector').attr('href');