Convert HTMLCollection to an array with JavaScript
Asked Answered
R

1

5

I want to get all the HTML elements with the class "Box" and then that collection convert it to an Array so i can acces each element throught position.

This is the code i made:

function BoxAppearence() {
    
    var BoxCollection = document.getElementsByClassName("Box");
    console.log(BoxCollection)
    var Box = BoxCollection.split("");
    console.log(Box)
    
    console.log(Box[12])
}

BoxAppearence();
Ramie answered 8/7, 2021 at 15:21 Comment(4)
var BoxCollection = Array.from(document.getElementsByClassName("Box")); should do what you wantBernice
This is my code rn: ``` function BoxAppearence() { var Box = Array.from(document.getElementsByClassName("Box")); console.log(Box); console.log(Box[12]); } BoxAppearence(); ``` But in console it's shows: [] and undefinedRamie
As you can see in this JSFiddle snippet, it works; are you sure you provided the correct class name (remember JavaScript is case-sensitive and "Box" is not the same as "box")? Are you sure your page contains elements with the "Box" class? Are you sure you are executing the function after the DOM has completely loaded?Bernice
Does this answer your question? Most efficient way to convert an HTMLCollection to an ArrayOutdistance
B
16

As mentioned in the comment, you can convert your HTML collection to an array by using Array.from().

Anyway, if your only reason for converting the collection to an array is being able to access an element by its index/position, as you can see from the code snippet below, you can do it also with an HTML collection (although actually you would be using an object "key" rather than an index).

function BoxAppearence() {
  var BoxCollection = document.getElementsByClassName("Box");
  var BoxArray = Array.from(BoxCollection);
  
  console.log("### BoxCollection ###");
  console.log("Is 'BoxCollection' an array?", Array.isArray(BoxCollection));
  console.log(BoxCollection);
  console.log(BoxCollection[12])
  console.log('\n\n');
  console.log("### BoxArray ###");
  console.log("Is 'BoxArray' an array?", Array.isArray(BoxArray));
  console.log(BoxArray);
  console.log(BoxArray[12]);
}

BoxAppearence();
<div class="Box">box1</div>
<div class="Box">box2</div>
<div class="Box">box3</div>
<div class="Box">box4</div>
<div class="Box">box5</div>
<div class="Box">box6</div>
<div class="Box">box7</div>
<div class="Box">box8</div>
<div class="Box">box9</div>
<div class="Box">box10</div>
<div class="Box">box11</div>
<div class="Box">box12</div>
<div class="Box">box13</div>
Bernice answered 9/7, 2021 at 7:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.