I have links set up like so:
HTML:
<a href="www.example1.com" class="some-link">
<a href="www.example2.com" class="some-link">
<a href="www.example3.com" class="some-link">
<a href="www.example4.com" class="some-link">
I want to get the href
s that the <a>
tags contain. I tried to iterate through each link like so:
Javascript / jQuery:
for (x=0; x < 5; x++) {
link = $(".some-link")[x].attr("href");
console.log(link);
}
When I try this, I get the error TypeError: $(...)[x].attr is not a function
. What's the issue? Thanks.
You need to use eq()
here, since $(".some-link")[x]
returns dom object attr()
method can only use with jQuery object. So you nee to use eq(x)
or :eq()
for (x=0; x < 5; x++) {
link = $(".some-link").eq(x).attr("href");
console.log(link);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="www.example1.com" class="some-link">
<a href="www.example2.com" class="some-link">
<a href="www.example3.com" class="some-link">
<a href="www.example4.com" class="some-link">
<a href="www.example4.com" class="some-link">
or you can use each()
method instead
$(".some-link").each(function(){
var link=$(this).attr("href");
console.log(link);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="www.example1.com" class="some-link">
<a href="www.example2.com" class="some-link">
<a href="www.example3.com" class="some-link">
<a href="www.example4.com" class="some-link">
<a href="www.example4.com" class="some-link">
or more simple way use attr()
with callback
$(".some-link").attr("href",function(i,link){
console.log(link);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="www.example1.com" class="some-link">
<a href="www.example2.com" class="some-link">
<a href="www.example3.com" class="some-link">
<a href="www.example4.com" class="some-link">
<a href="www.example4.com" class="some-link">
The [1]
indexer (equivalent to .get()
) does not return a jQuery element, but a DOM element. Try
var link = $(".some-link").eq(x).attr("href");
As a side note, you probably want to declare your variable using var
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With