user1079538
user1079538

Reputation: 9

Loop in Jquery by using eq

I want to use loop to display the title of link . is included in div "test" I write code like this:

$("#test a").each(function (index) {
    alert($("#test a:eq(index)").attr("title"));
})

I get the result "Undefined". If I change

alert($("#test a:eq(0)").attr("title"))

it works normal. Anybody can help me???. Thanks for your help

Upvotes: 0

Views: 120

Answers (3)

Midio
Midio

Reputation: 36

For the sake of clarity I always specify both the key and value parameters. k being the index count and v being the selector object e.g

$("#test a").each(function(k, v){
    alert($("#test a:eq(" + k + ")").attr("title"));
});

Heres a working example

Upvotes: 0

Esailija
Esailija

Reputation: 140228

.each is already looping through the a elements, just alert the title:

$("#test a").each(function () {
    alert( this.title );
});

Upvotes: 3

Joseph Silber
Joseph Silber

Reputation: 220026

You're using index as part of the string. You have to concatenate the value of index:

$("#test a").each(function(index) {
    alert( $("#test a:eq(" + index + ")").attr("title") );
});

But you don't really need that. You could simply use the this keyword:

$("#test a").each(function() {
    alert( $(this).attr("title") );
});

The this keyword will always be the current node in the loop.

Upvotes: 2

Related Questions