Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: reverse an array of document.getElementByClassName

Tags:

javascript

i have this variable that is:

var stars = this.parentNode.children

and its value is:

[span.rate, span.rate, span.rate.rated, span.rate.rated, span.rate.rated]

Now i want to reverse it, but if i try:

stars.reverse()

I obtain

Uncaught TypeError: stars.reverse is not a functionupdateRateStar @ app.js:75(anonymous function) @ app.js:98

I cannot understand why it works with an array like:

[1,2,3]

So if i try:

[1,2,3].reverse()

it works. Thus i cannot understand the problem

like image 201
Francesco Avatar asked Jan 01 '16 21:01

Francesco


People also ask

How do I iterate over document getElementsByClassName?

Iterate Through Elements Returned by getElementsByClassName getElementsByClassName method is to use the for-of loop. We call document. getElementsByClassName with 'slide' to return an HTML element collection object with all the divs. Then we use the for-of loop to loop through each item.

What does getElementsByClassName () function return?

Document.getElementsByClassName() The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s). When called on the document object, the complete document is searched, including the root node.

How do you reverse a NodeList?

The simplest way to do that is with a forEach() loop. The querySelectorAll() returns a NodeList, and not all browsers have a NodeList. forEach() method. You can polyfill it, or convert the NodeList into an Array so that you can use the Array.

Is getElementsByClassName an array?

The getElementsByClassName() method returns an array-like of objects of the child elements with a specified class name. The getElementsByClassName() method is available on the document element or any other elements. The method returns the elements which is a live HTMLCollection of the matches elements.


2 Answers

You can't call Array.prototype.reverse on NodeListCollection. Instead, you should use:

var stars = [].slice.call(stars, 0).reverse()
like image 57
Soheil Karami Avatar answered Sep 26 '22 01:09

Soheil Karami


Use

var revArray = Array.prototype.slice.apply( a ).reverse()

The reason is that you have a NodeList and not an Array there. Both behave similarly in many cases, but the NodeList does not have the array methods.

With the

Array.prototype.slice.apply( a )

part, we convert the NodeList to an array, which can than be reversed.

like image 35
Sirko Avatar answered Sep 24 '22 01:09

Sirko