Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: $(...)[1].attr is not a function

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 hrefs 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.

like image 860
Pav Sidhu Avatar asked Oct 08 '15 18:10

Pav Sidhu


2 Answers

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">
like image 137
Pranav C Balan Avatar answered Oct 06 '22 15:10

Pranav C Balan


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.

like image 33
alexn Avatar answered Oct 06 '22 13:10

alexn