...">

JQuery attr () only works for the first element

I don’t understand why attr () is called only once,

my html

<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 the "title" from all abbr , so I wrote the following query

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

So he must give me back

 first second . . . 

but the output is only "first" ,

but if you write

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

then I get the correct conclusion. but I don’t think this is the right approach, so any body, please tell me where I am wrong.

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

thanks

+4
source share
2 answers

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

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

Here is a very easy way. get all abbr elements from the myTable table and give their name.

http://jsfiddle.net/cngpd/

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

All Articles