Utilize div elements and apply CSS styles: Comparing HTMLCollections and Arrays

Looking for a solution to this issue:

var ArrayTest = [1,2,3,4,"test"];
var ArrayTest2 = document.getElementsByClassName('mydiv');
ArrayTest2.forEach( function(){
    this.style.display = 'none'; 
});

Although ArrayTest returns as an Array, ArrayTest2 returns as an HTMLCollection and forEach results in an "undefined" type error.

Is there a way to gather an array of elements sharing the same classname and apply the same CSS to each one?

Answer №1

Here is a different approach to achieve the same result, utilizing a CSS class and the power of jQuery for simplicity:

$(".mydiv").addClass("hide-element");

Then, add the following style in your CSS file:

.hide-element {
    display: none;
}

If you prefer setting the display attribute inline, you can do so with this jQuery snippet:

$(".mydiv").css("display", "none");

Update

Alternatively, here's how you can achieve this using pure JavaScript:

for (var j = 0; j < elementsArray.length; j++) {
   elementsArray[j].style.display = "none"; 
}

Answer №2

To convert an HTMLCollection to an array, you can utilize the Array.prototype.slice method.

For instance:

var ArrayTest2 = document.getElementsByClassName('mydiv');

ArrayTest2 = Array.prototype.slice.call(ArrayTest2);

ArrayTest2.forEach( function(element){
    element.style.display = 'none'; 
});

Detailed Explanation:

Using Array#slice helps in transforming the collection into an array, enabling the use of Array#forEach

This enables looping through each element and easily manipulating the display style.


Another Example:

You can also achieve this by directly using Array.prototype.forEach without involving the slice step.

Array.prototype.forEach.call(document.getElementsByClassName('mydiv'), function(element) {
    element.style.display = 'none';
});

Answer №3

const divElements = Array.from(document.getElementsByClassName('mydiv'));

In modern JavaScript, you can use the Array.from method to convert an Array-like object into a real array. This is a cleaner and more efficient way compared to using the spread operator in ES6 (though you may need Babel or other compilers for compatibility).

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

toggle the hiddenpost class when it reaches the top of the screen

Today I find myself in the unfamiliar position of needing to ask for help, as I have been unable to solve this problem on my own. Despite extensive searching and even using advanced search techniques, I still haven't found the solution I need. My iss ...

What is the best method for importing Bootstrap into SvelteKit?

I am currently working on a SvelteKit website. I have integrated Bootstrap 5 into my project by adding it to the app.html file provided by the SvelteKit Skeleton starter project: <!-- Bootstrap styles and javascript --> <link rel="stylesheet ...

Creating an interactive table populated with data from a JSON file using JavaScript

Using this JSON data as the basis for developing a table, I am facing challenges in adding rows based on columns. [ { "authType": "BasicAuth", "phases": [ { "type": "Development", "keys":[{ "username": "developer" },{ "password": ...

Incorporate fresh data into the updated vue3-chart

I am experiencing an issue with my Chart.js Chart in a Vue component that uses vue3-chart-v2. Initially, everything works fine until I attempt to update the data. Currently, I am utilizing a watcher to monitor changes in the data. While the watcher functi ...

Tips for effectively interpreting a json string

Trying to extract specific fields from a JSON string and display them on an HTML page, but encountering the following error: SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data This is the JSON being sent: { "Order0& ...

Leveraging d3.js for sending multiple JSON requests and mapping data to various elements

I've been working on setting up a configuration page where users can reconcile unmatched data by choosing from a list of possible matches. The backend generates the list of items that need to be matched, and then a JS function is used to fetch the lis ...

"I'm trying to incorporate react-datepicker into my ReScript application, but I'm struggling to

I am attempting to incorporate an external library like react-datepicker into my project. Below is the code snippet and how I am using it: module DatePicker = { @react.component @module("react-datepicker") external make: () => React.eleme ...

How to select a unique, non-repeating element from an array using Ruby?

I have a list of questions and I'm looking to select a random one that doesn't repeat until all the questions have been asked. If all questions have been asked, then the process should start again. I want to create a method or function for this. ...

Error: AppModule requires an array of arguments in order to function properly

Upon successfully compiling my Angular application and running ng serve, I encountered the following error in the browser console. AppComponent_Host.ngfactory.js? [sm]:1 ERROR Error: Arguments array must have arguments. at injectArgs (core.js:1412) at c ...

Can the protractor event queue or control flow be modified?

Currently, I am involved in a project focused on automation. We are utilizing protractor and jasmine2 to automate tasks on our angularjs+nodejs application. One specific scenario I am working on involves uploading a file. After clicking the upload button, ...

Permitting the user to remove an option from the antd select widget

I have integrated the antd select component in my React application and I am looking to add a delete option for users. For more details, please refer to the image below:https://i.sstatic.net/ZP4PP.png This is how I attempted to implement it: {tasks.map( ...

Tips on adjusting weight and height in CSS to ensure responsiveness as the screen size decreases

Is there a way to set the weight and height in CSS so that they remain responsive when the screen size is reduced? Currently, I am resizing using PHP before storing but I am considering using HTML and CSS or JavaScript instead. Is there a solution for this ...

What is the best way to remove the excess space beneath a column in Bootstrap 5?

I made the changes as instructed, but when I view it on a mobile phone, the blue box and pink box are not aligned as I want them to be. I have attached a screenshot for reference, and I would like the mobile version to mirror the desktop version. I am uns ...

What is the best way to choose the following 3 elements that are siblings of a randomly positioned element?

I need assistance with selecting the next three siblings of a grid of divs on a board. Although I considered using nextUntil(), the issue is that the ids of these siblings are randomly generated upon loading, so they are not fixed. I am unsure how to solve ...

What steps can I take to avoid the replacement of a default user image in my Firebase 9 application?

I have been working on a chat application using React 18 and Firebase 9. One issue I encountered is with the Register form, specifically with an input field of type file for uploading the user's avatar. The avatar field in the form is not mandatory, ...

Scan across a lineup of pictures

I am looking to showcase a series of images in a horizontal alignment, but I want to avoid overloading the screen width. My goal is to allow users to navigate through the images using their mouse - when they move right within the image container, I want t ...

Achieving a function call within a Backbone view in Backbone.js

Is it possible to call the plotPort function from the plotLoc function using this.plotPort() instead of self.plotPort()? It seems to not work for Internet Explorer when using self.plotPort(). As a workaround, I added an event to lLoca upon reset to call ...

Get the file from the web browser

Hey there, greetings from my part of the world. I have some straightforward questions that I'm not sure have simple answers. Currently, I am working on a web application using the JSP/Servlet framework. In this app, users can download a flat text fil ...

The issue with the sticky menu not functioning properly may be due to the use

Hey there, I'm facing an issue with the Navbar Menu (White Bar) on my website. It is working perfectly fine and sticking to the top as expected. However, the problem arises when I click on the Menu - the Sticky class stops working. Upon investigating, ...

Is there a way to eliminate the scrollbar from the purecss navbar?

My website utilizes pure.css and the navbar has more elements than can fit on a small screen without scrolling. This results in an unwanted scrollbar appearing. I want the navbar to remain at the top so that it scrolls along with the content. However, when ...