Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

question from:https://stackoverflow.com/questions/7055053/jquery-select-attributes-into-an-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
134 views
Welcome To Ask or Share your Answers For Others

1 Answer

****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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...