开发者

jQuery select attributes into an array

开发者 https://www.devze.com 2023-03-27 19:10 出处:网络
What\'s the most elegant way to get this array [10, 20, 30, 40, 50] 开发者_如何学C out of this list

What's the most elegant way to get this array

[10, 20, 30, 40, 50]
开发者_如何学C

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.


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

jQuery select attributes into an array


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

jQuery select attributes into an array


I think that map works just fine.. just not in the chain.

var vals = $.map($("li[value]"), function(li) {
    return $(li).attr("value");
});


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


Speaking of elegant code, we can get a better solution using Underscore in combination with jQuery:

_($('ul li').toArray()).map(function(e) { return e.value })

And while we're at it, why not dump Javascript for CoffeeScript:

_($('ul li').toArray()).map (e) -> e.value

;-)

0

精彩评论

暂无评论...
验证码 换一张
取 消