gurkensaas
gurkensaas

Reputation: 913

Get certain attribute of HTMLCollection

So I was wondering if there was a way to get e.g. all value's of an HTMLCollection. So something like this:

var users = document.getElementsByName('users')
var userLength = []
for (var i = 0; i < users.length; i++) {
    userLength.push(users[i].value);
}
userLength.sort(function(a, b){return b - a});
console.log(userLength);

...but in one line, so more like this:

document.getElementsByName('users').value

If you want to run this, it was written for the sites-section on stackexchange. And no, the second one doesn't work.

I can't use jQuery, so this is not an option for me.

Upvotes: 0

Views: 1114

Answers (1)

Mamun
Mamun

Reputation: 68933

First get element array getting using Spread syntax (...), then use Array.prototype.map() to get the all the values. Finally chain the sort method on the returned results:

var users = document.getElementsByName('users')
var userLength = [...users].map(el => +el.value).sort(function(a, b){return b - a});
console.log(userLength);
<input name="users" value="11"/>
<input name="users" value="22"/>

Upvotes: 1

Related Questions