Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of element of the same class javascript

How get an array of the values of elements which have same class?

When I do this I get only the first element, but I want a whole array:

var classes = document.querySelector(".klass").value;
alert(classes); //Outputs only the first element

And I want to get a full array of the values of the inputs:

<input type="text" class="klass" />
<input type="text" class="klass" />
<input type="text" class="klass" />

Is that possible?

like image 664
Maroxtn Avatar asked Apr 23 '26 18:04

Maroxtn


2 Answers

Use document.querySelectorAll to retrieve a NodeList (see also the section "How can I convert NodeList to Array?") then cast it to an array and map a function that returns each element's value.

var classesNodeList = document.querySelectorAll(".klass");
var classes = Array.prototype.slice.call(classesNodeList).map(function(element) {
    return element.value;
});

Update


As stated in the comment by Ginden, a shorter way to do this is to pass the NodeList to Array.prototype.map using Function.prototype.call

var classesNodeList = document.querySelectorAll(".klass");
var classes = Array.prototype.map.call(classesNodeList, function(element) {
    return element.value;
});
like image 97
axelduch Avatar answered Apr 26 '26 08:04

axelduch


For such a simple CSS selector expression, I would use getElementsByClassName and give it the class name, rather than querySelectorAll. getElementsByClassName is generally faster than using querySelectorAll by several orders of magnitude. See this jsperf.

var classes = document.getElementsByClassName("klass"); // Do not use a period here!
var values = Array.prototype.map.call(classes, function(el) {
    return el.value;
});

getElementsByClassName is usually faster than querySelectorAll. Browsers index elements by class name already to optimize the speed of CSS transformations. getElementsByClassName returns an HTMLCollection element, so it does not have the Array methods and you need to use Array.prototype... on this too.

like image 30
Louis Avatar answered Apr 26 '26 06:04

Louis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!