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();
4
  • 1
    var BoxCollection = Array.from(document.getElementsByClassName("Box")); should do what you want Commented Jul 8, 2021 at 15:24
  • 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 undefined Commented Jul 8, 2021 at 17:03
  • 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? Commented Jul 9, 2021 at 7:15
  • Does this answer your question? Most efficient way to convert an HTMLCollection to an Array Commented Jul 9, 2021 at 7:57

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.