Most efficient way to convert an HTMLCollection to an Array
var arr = Array.prototype.slice.call( htmlCollection )
will have the same effect using "native" code.
Edit
Since this gets a lot of views, note (per @oriol's comment) that the following more concise expression is effectively equivalent:
var arr = [].slice.call(htmlCollection);
But note per @JussiR's comment, that unlike the "verbose" form, it does create an empty, unused, and indeed unusable array instance in the process. What compilers do about this is outside the programmer's ken.
Edit
Since ECMAScript 2015 (ES 6) there is also Array.from:
var arr = Array.from(htmlCollection);
Edit
ECMAScript 2015 also provides the spread operator, which is functionally equivalent to Array.from
(although note that Array.from
supports a mapping function as the second argument).
var arr = [...htmlCollection];
I've confirmed that both of the above work on NodeList
.
A performance comparison for the mentioned methods: http://jsben.ch/h2IFA
How do I convert a HTMLCollection into an array, without emptying it?
Try using this:
setTimeout(() => {
this.convertToArray();
});
convertToArray() {
const shapesHC = document.getElementsByClassName('shape');
const shapesArrHCSpread = [...(shapesHC as any)];
console.log(shapesArrHCSpread);
}
How do I Convert a HTML Collection into an array, without emptying it? #2
The code cannot work before you are using base
before initializing it. Placing the initialization before using it makes it work.
Here I modified it: https://jsfiddle.net/tk78z5gq/
Is HTMLCollection An Array?
No, it's an HTMLCollection
, not an Array
.
It has Array-like characteristics, like numeric properties, and a .length
property, but it does not inherit from Array.prototype
. Therefore it does not have the standard Array
methods, and so should be seen as being different.
Another significant difference is that HTMLCollection
is a "live" collection, which means that it updates as the DOM updates. If you remove one of its nodes from the DOM, it will be removed from the HTMLCollection
automatically.
efficient way of creating an event listener for multiple IDs
Change the id to class, and itarete through all the elements to add the same eventlistener to each.
const players = document.querySelectorAll(".qmedia")
Array.from(players).forEach(
player=>player.addEventListener("playing", event => {
if (player.requestFullscreen)
player.requestFullscreen();
else if (player.webkitRequestFullscreen)
player.webkitRequestFullscreen();
else if (player.msRequestFullScreen)
player.msRequestFullScreen();
}))
<div class="qmedia">Click</div>
<div class="qmedia">Click</div>
<div class="qmedia">Click</div>
<div class="qmedia">Click</div>
<div class="qmedia">Click</div>
Using Array class methods for HTMLCollection DOM traversel in ES6
The easiest approach is to convert it to an array first with Array.from
:
const collection = Array.from(document.querySelector('#tblEvents').rows);
What is a size efficient way to encode a JSON array of array of numbers into a URL
Ok, so base64 is not for compression.
But I just (re)invented a compression method and base64 is part of it. It compress to about 65% indeed. The idea is to compress each pair of digits to a 2 digit hex number which is one ascii char. Then base64 it for safety.
var data = [
[0.3, 2.1, -0.04, 32, 0, 54],
[9, 593, 82, 593, 1360, 593, 82, 582, 1344, 4676, 1344, 593, 82, 593, 82, 578, 1344, 593, 82, 577, 1344, 593, 82, 567, 1328, 593, 82, 4662, 1328, 593, 82, 4662, 1328, 593, 82, 577, 1344, 593, 82, 4674, 1344, 582, 1344, 594, 1360, 4693, 1360, 599, 1360, 4705, 1376, 582, 1344, 581, 1344, 581, 1344, 4677, 1344, 4678, 1344, 593, 1360, 4690, 1360],
[9, 593, 82, 593, 1360, 593, 82, 582, 1344, 4676, 1344, 593, 82, 593, 82, 578, 1344, 593, 82, 577, 1344, 593, 82, 567, 1328, 593, 82, 4662, 1328, 593, 82, 4662, 1328, 593, 82, 577, 1344, 593, 82, 4674, 1344, 582, 1344, 594, 1360, 4693, 1360, 599, 1360, 4705, 1376, 582, 1344, 581, 1344, 581, 1344, 4677, 1344, 4678, 1344, 593, 1360, 4690, 1360],
];
function encode_char(c) {
if (c == '[') return 'a';
if (c == ']') return 'b';
if (c == ',') return 'c';
if (c == ' ') return 'd';
if (c == '.') return 'e';
if (c == '-') return 'f';
return "" + c;
}
function decode_char(c) {
if (c == 'a') return '[';
if (c == 'b') return ']';
if (c == 'c') return ',';
if (c == 'd') return ' ';
if (c == 'e') return '.';
if (c == 'f') return '-';
return "" + c;
}
function encode_string(str) {
var result = "";
var arr = str.split("");
if (arr.length % 2) {
arr.push(" ")
}
for (var i = 0; i < arr.length; i += 2) {
var c1 = encode_char(arr[i])
var c2 = encode_char(arr[i + 1])
var hex = "" + c1 + c2
result += String.fromCharCode(parseInt(hex, 16));
}
return result;
}
function decode_string(str) {
var result = "";
var arr = str.split("");
for (var i = 0; i < arr.length; i += 1) {
var char = arr[i]
var hex = char.charCodeAt(0).toString(16);
hex = hex.length < 2 ? "0" + hex : hex;
var c1 = decode_char(hex.slice(0, 1))
var c2 = decode_char(hex.slice(1, 2))
result += "" + c1 + c2
}
return result.trim();
}
function encode_integers(str) {
var result
result = encode_string(str);
result = btoa(result)
result = encodeURIComponent(result)
return result;
}
function decode_integers(str) {
var result
result = decodeURIComponent(str);
result = atob(result)
result = decode_string(result)
return result;
}
var json = JSON.stringify(data);
console.log(json.length, json)
var str = encode_integers(json);
console.log(str.length, str)
var json = decode_integers(str)
console.log(json.length, json)
console.log("compression ratio", (str.length / json.length).toFixed(2))
Related Topics
Using "Object.Create" Instead of "New"
Determining Image File Size + Dimensions via JavaScript
Why Does the Month Argument Range from 0 to 11 in JavaScript's Date Constructor
How to Get a JavaScript Object's Class
Node.Js on Multi-Core MAChines
Reactjs - Does Render Get Called Any Time "Setstate" Is Called
Selecting Null: What Is the Reason Behind Selectall(Null) in D3
Filter Object Properties by Key in Es6
Const in JavaScript: When to Use It and Is It Necessary
How to Open a Bootstrap Modal Window Using Jquery
React Native - Image Require Module Using Dynamic Names
How to Capture an Arbitrary Number of Groups in JavaScript Regexp
Working with Select Using Angularjs's Ng-Options
How to Set the Value Property in Angularjs' Ng-Options
Javascript/Jquery: $(Window).Resize How to Fire After the Resize Is Completed