Maroxtn
Maroxtn

Reputation: 693

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?

Upvotes: 3

Views: 24054

Answers (4)

axelduch
axelduch

Reputation: 10849

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;
});

Upvotes: 7

Louis
Louis

Reputation: 151380

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.

Upvotes: 3

Hydrothermal
Hydrothermal

Reputation: 5081

You need to loop through your array of elements and get the value of each one.

var classes = document.querySelectorAll(".klass").value,
    values = [];

for(var i = 0; i < classes.length; i++) {
    values.push(classes[i].value);
}

Note that this may not be as clean as using [].map, but is a good deal faster.

Upvotes: 2

udalmik
udalmik

Reputation: 7988

You can use querySelectorAll method first and then use array's map function to retrieve the result:

var elements = document.querySelectorAll('.klass');
var values = [].map.call(elements, function(e) {
  return e.value;
});

Upvotes: 0

Related Questions