Transforming an HTMLCollection into an array using JavaScript

I am looking to retrieve all the HTML elements that have the class "Box" and then convert that collection into an Array so I can access each element by its position.

Below is the code I wrote:

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

BoxAppearence();

Answer №1

If you're looking to transform your HTML collection into an array, one way to achieve this is by utilizing the Array.from() method.

However, if your primary objective in converting the collection to an array is for easy element access based on index or position, the code snippet below demonstrates that it's possible to do so using the HTML collection itself (although it involves treating keys as opposed to traditional indices).

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to setting up index.js with ApiProvider in the Redux Toolkit (RTK)

Have you ever considered customizing the index.js file in the root directory based on ChatGPT's recommendations? I'm not entirely convinced that it's the most common practice. What are your thoughts on this approach? // Here is an example of ...

PHP: A guide to traversing a multi-dimensional array and printing out the arrays within it rather than the individual elements within those arrays

Usually when I search, I find what I need, but this time I'm a bit lost. I decided to create a multidimensional array using the following approach: Below is the code - from input to push: This is the text entered into the textarea: VIE-CAI HA ...

Unable to modify the array while attempting to incorporate additional features

My form consists of a set of fields that need to be submitted to the backend upon completion. These fields can be dynamically added through the "add more" functionality. View Code Fiddle For instance, if I use the "add more" feature three times, the valu ...

Creating session variables in Joomla using checkboxes and AJAX

I'm currently working on implementing session variables in Joomla with AJAX when checkboxes are selected. Below is the code snippet from select_thumb.ajax.php file: $_SESSION['ss'] = $value; $response = $_SESSION['ss']; echo ...

Show rows in the table based on the child nodes retrieved from the backend database

I am facing a minor issue with a table Below is the table <table> <thead> <th>Name</th> <th ng-repeat="value in drilldownReport.columns"> {{ drilldownReport.columnNames[value] }} ...

Can AngularJS Filters be used to convert a number into a string, but not the other way around?

After researching Angular JS filters, I discovered that the number filter is used to format a number as a string. However, there doesn't seem to be a built-in filter for converting a string to a number. In an attempt to solve this issue, here is so ...

Executing a Drupal rule using JavaScript: A step-by-step guide

I'm facing a challenge when trying to activate a Drupal rule using JavaScript code. lowerLayer[image.feature_nid].on("dragend", function() { var position = kineticImage.getPosition(); var layerPosition = this.getPo ...

Is it possible to transmit the survey findings through a telegram?

Just finished creating a survey using the platform . Here are the results: Data format: {"question1":["item1"],"question2":["item2"],"question3":["item2"],"question4":["item2" ...

Managing all AJAX success events in one centralized location using jQuery

In a particular situation, I find myself needing to handle all jquery success events in one centralized location. This is because I want a specific function to be called after every ajax success event occurs. While I am aware that I can use $.ajaxComplete ...

Having trouble getting multiple OR conditions in a PHP if() statement to work correctly. I've checked the array values and everything seems fine. Any idea what I

My if statement was working perfectly fine until I decided to add two additional || (or) operators. This is the snippet of code that's causing me trouble: if ($planDetails['Company']['name'] != 'company1' || $planDetail ...

Guide to clicking on elements with selenium framework

Struggling to scrape a web page from the bookmyshow site using selenium. Encounter two popups upon loading the page, trying to click the necessary buttons to close them. Facing issues locating these elements despite using sleep() to ensure complete page lo ...

What is the best way to pass a dynamically allocated array between different programs in C?

Despite examining multiple examples, I am still struggling with a particular issue. In my header file, I have an extern int *sharedarray[]. Then, in my three separate .c files, I define it as int *sharedarray[]. Within the first .c file, I allocate the nec ...

Trigger an Angular2 component function from an HTML element by simply clicking a button

I'm just starting out with TypeScript and Angular2 and encountering an issue when trying to call a component function by clicking on an HTML button. When I use the **onclick="locateHotelOnMap()"** attribute on the HTML button element, I receive this ...

Jackson is able to deserialize an array of objects into a POJO

So I am working with a JSON file that looks like this: { "results":[ "result":{}, "result":{} ] } My goal is to deserialize this JSON data into a Java object that consists of an array of result objects. public class Fo ...

Complex recurrent operation

Can anyone assist me in solving this complex loop? I need to call 5 API URLs, each a specific number of times before moving on to the next URL in sequence and then starting over again. https://www.example1.com should be called 4 times https://www.example2 ...

All about UI-Grid: Mastering the process of selecting records on the current page with the convenient selectAll checkbox option

In the UI-grid, there is a "select All" checkbox that, when checked, selects all the records visible on the current page and other pages. Query - Is there a way to select rows displayed only on the current page? You can check out the example on plunker: ...

Is it possible to observe a shift in the current locale of internationalization (i18n)?

Is there a way to trigger a function when the language/locale changes with i18n? Can I achieve this using Vuex, or is there a specific method in vue-i18n to accomplish this? ...

The page is having trouble loading images

My goal is to display sliding images in a web application using Bootstrap carousel. The images are fetched from the backend and stored in the 'images' state. Below is the JSON format of the data that is retrieved: images:[ { SNO:'1', NA ...

Unraveling the Mystery of the JavaScript forEach() Function

Exploring the use of nodejs in Ubuntu and delving into the MDN documentation for the JavaScript forEach() method. While aware of alternative methods, I find that hands-on learning suits me best; my current goal is to create a unique array named copy, conta ...

Struggling to send data to Wufoo API using PHP and AJAX

I'm still getting the hang of PHP and attempting to send data to a Wufoo Form that includes the fields shown below: https://i.sstatic.net/yoOgy.png However, when trying to POST information to it, I keep receiving a 500: Internal Server Error along w ...