Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery select attributes into an array

Tags:

jquery

What's the most elegant way to get this array

[10, 20, 30, 40, 50] 

out of this list

<ul>       <li value="10">Item One</li>     <li value="20">Item Two</li>     <li value="30">Item three</li>     <li value="40">Item Four</li>     <li value="50">Item Five</li> </ul> 

using jQuery.

like image 973
David Weng Avatar asked Aug 14 '11 04:08

David Weng


People also ask

What is. attr in jQuery?

jQuery attr() Method The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.

How to find attribute name in jQuery?

To get the name, you'd use $(selector). attr('name') which would return (in your example) 'xxxxx' .

How to get array attribute in jQuery?

var elements = (document. getElementsByTagName('li')); var vals = []; for(var i=0;typeof(elements[i])!

How to get attribute data in jQuery?

Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to find the data-id attribute of an HTML element.


1 Answers

****edit****

ok the glove has been thrown down...

var elements = (document.getElementsByTagName('li')); var vals = []; for(var i=0;typeof(elements[i])!='undefined';vals.push(elements[i++].getAttribute('value'))); 

no library 3 lines of code...

epicly faster

enter image description here


var myVals = []; $('li','ul').each(function(){   myVals.push($(this).attr('value')); }); 

and using jquery's map function...

var myVals = []; $('li','ul').map(function(){   myVals.push($(this).attr('value')); }); 

and they are both equally as fast.. http://jsperf.com/testing-stuff enter image description here

like image 139
samccone Avatar answered Sep 19 '22 21:09

samccone