44

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.

4 Answers 4

68

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

Sign up to request clarification or add additional context in comments.

9 Comments

map would not really make sense... seeing as you are just extracting values and not DOM elements
@samccone But can return values :p
ha ok you win.. if we want to save like 14 characters we can do it that way :)
absolutely it is faster! And a great solution. I'd use pure javascript most of the time too. However, the question asked for a jQuery solution.
+1, it's crazy how lower-level code can be faster! Elegance comes at a price.
|
33

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

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

2 Comments

@samccone interesting that "no library" is preferred for a question specifically asking for a solution "using jquery".
This is also the "most elegant" as the question poses. Speed is irrelevant for such a small run, but still nice to see.
8
var outVal = [];
$('ul li').each(function(idx, el){
    outVal.push($(this).attr('value'));
});

Comments

5

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

;-)

7 Comments

jQuery already has $.map and .map (works sorta like flatmap). But +1 for using a map.
Yes, I forgot that jQuery had that one, I'm totally hooked on Underscore it seems!
ha @nicolas ... nice I got mine down to 3 lines and no libraries :)
Thanks Nicolas, what's _? I've never seen it before!
It's the Underscore.js function, an awesome library that I hope will become as common as jQuery one day: documentcloud.github.com/underscore
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.