Saurabh Bayani
Saurabh Bayani

Reputation: 3500

jQuery attr() working for first element only

I don't understand why attr() get called for only one time,

my html is

<table id="myTable">
    <tbody>
        <tr>
            <td>...</td>
            <td>...</td>
            <td>
                <abbr title='first'>Demo1</abbr>
            </td>
        </tr>
        <tr>
            <td>...</td>
            <td>...</td>
            <td>
                <abbr title='second'>Demo2</abbr>
            </td>
        </tr>
        .
        .
        .
    </tbody>
</table>

now I want to get "title" of all abbr so wrote following query

$(document).ready(function () {
    console.log($('#myTable tr td:nth-child(3) abbr').attr("title"));
}

So, it should return me

first
second
.
.
.

but output is only "first",

but if write

var oRows = $('#myTable tbody tr');
$.each(oRows, function (i) {
    console.log($(this).children('td:nth-child(5)').children().attr("title"));
});

then I am getting right output. but I don't think it is a proper approach, so can any body please tell me where I am going wrong.

Also I read this answer, but still I am not clear

Thank you

Upvotes: 4

Views: 2168

Answers (3)

Leschge
Leschge

Reputation: 164

This way you get it for every element:

JS

  $(".ele_title").click(function(){
    var value = $(this).attr('title');
    alert(value);
  });

HTML

<abbr class='ele_title' title='first'>Demo1</abbr>
<abbr class='ele_title' title='second'>Demo1</abbr>
<abbr class='ele_title' title='third'>Demo1</abbr>

Upvotes: -1

Blender
Blender

Reputation: 298106

.attr() returns the attribute of the first element. If you want the attributes of all of the matched elements, use map:

var titles = $('#myTable tr td:eq(3) abbr').map(function() {
    return $(this).attr('title');   // or just `return this.title`
}).get();

Upvotes: 5

user2063626
user2063626

Reputation:

Here is a much simple way. get all abbr elements from table myTable and give their title.

http://jsfiddle.net/cngpd/

$("abbr", $("#myTable")).each(function () {
    console.log($(this).attr('title'));
})

Upvotes: 1

Related Questions