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.
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.
To get the name, you'd use $(selector). attr('name') which would return (in your example) 'xxxxx' .
var elements = (document. getElementsByTagName('li')); var vals = []; for(var i=0;typeof(elements[i])!
Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to find the data-id attribute of an HTML element.
****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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With