0

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.

3
  • Your example doesn't use innerText it uses value. Start there. Maybe if you add a minimal reproducible example to your question we can help debug. Commented Aug 25, 2021 at 12:51
  • I Guess map should be enough here Commented Aug 25, 2021 at 12:54
  • Sure you can do it in one line.... delete the returns. :) There is nothing that can do it in one like you want. But map() is the way to go. document.querySelectorAll("[name='users']").map(x => x.value) Commented Aug 25, 2021 at 13:00

1 Answer 1

1

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"/>

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

4 Comments

I know this is not really part of the question but is there a way to get the program to return the text like a document.getElementsByName();-statement would?
@gurkensaas, do you mean the value in the string format?
If I now try to do it with strings, it gives me NaN's. Is there a way to also get strings?
@gurkensaas, remove the + from +el.value....i,e: [...users].map(el => el.value).sort(function(a, b){return b - a});

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.