Tips for choosing multiple components

I've created a script where clicking on a td tag in the table will change the background color of a div. However, I want to be able to change the background color of multiple divs.

The issue is that with getElementById(), it can only select one div and not two.

Here is my CSS:

td {width:20px; height:20px;}
.result{width:200px; height:100px; margin:10px auto; background:green;}

My script looks like this:

function bgcolor(color){
        els = document.getElementByClassName('result');
        for(i in els){
            els[i].style.backgroundColor = color;
        }
    }

And here is my HTML code:

<table>
    <tr>
        <td style="background:red;" onclick="bgcolor('red')"></td><td style="background:blue;" onclick="bgcolor('blue')"></td>
    </tr>
    <tr>
        <td style="background:green;" onclick="bgcolor('green')"></td><td style="background:yellow;" onclick="bgcolor('yellow')"></td>
    </tr>
    <tr id="row">
        <td style="background:brown;" onclick="bgcolor('brown')"></td><td style="background:grey;" onclick="bgcolor('grey')"></td>
    </tr>
</table>
<div class="result"></div>

Where did I go wrong?

Answer №1

To easily change the background color of elements with a specific class, you can create a function that takes a color parameter. By using getElementsByClassName, which returns a collection of elements, you can loop through them and apply the desired background color:

function changeBgColor(color){
  let elements = document.getElementsByClassName('box');
  for(let i=0; i<elements.length; i++){
    elements[i].style.backgroundColor = color;
  }
}

You can then call this function like so:

changeBgColor('blue');

Answer №2

To begin, start by using the method document.getElementsByClassName.

Answer №3

When using getElementByClassName(classname), only the first element with the specified class will be returned. If you need to target all elements with that class, use

document.getElementsByClassName(classname)
(note the plural 'elements').

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

Dynamic generation causing Bootstrap tabs to malfunction

I have incorporated a bootstrap tab on my website, which is generated dynamically through ajax requests. While testing the static version of these tabs, everything was functioning perfectly. However, now that I am generating all tabs and panes dynamically ...

Tips for Inserting Text into a Table

I'm in need of creating a form that includes input text, color selection, and an add button. Once the button is clicked, I want the entered information to be displayed in a table. For example, if I type "Attend Selection Day" and choose "critical", t ...

In Javascript, POST tags are not conveyed within a single sentence

When there are multiple tags in the same sentence, only the first selected tag is being sent. What could be causing this issue? Check out the code on JSFiddle $(function(){ $('#lbl1').one('mouseover', functio ...

What is the process for modifying the headers of a post request in Express when

I have a Node/Express application and I'm looking to incorporate an image upload feature into an order form. While I can successfully use the action link in the HTML form to perform a POST request, I also want my JavaScript file associated with this ...

Ways to determine if an element is within the viewport and covers the full screen

I came across a solution on this website: Although, the solution mentioned is specifically for determining if an element is visible within the viewport. However: What I am trying to achieve is a bit different as I want to figure out if the element covers ...

Struggling to update a document fetched through a Mongoose model and handled as a promise

Check out update #2 for more detailed information I am encountering difficulties while trying to make a simple update to a document that has been retrieved by querying a container through a Mongoose model. The query using find has two populations, but oth ...

The border of the Material UI Toggle Button is not appearing

There seems to be an issue with the left border not appearing in the toggle bar below that I created using MuiToggleButton. Any idea what could be causing this? Thank you in advance. view image here view image here Just a note: it works correctly in the ...

Encountering a failure when trying to run npm in a React project

I've removed the .lock file and node_modules, then reinstalled, but it's still not working. Can someone assist me with fixing this? npm ERR! gyp ERR! node -v v16.13.0 npm ERR! gyp ERR! node-gyp -v v8.2.0 npm ERR! gyp ERR! not ok npm ERR! node-pr ...

Updating pictures on Bootstrap's project showcase template

I attempted to modify the source of an image by clicking on smaller ones using bootstrap’s template found at . Despite my efforts, I have not been able to achieve the desired result. (Any help is greatly appreciated!) I included id="myImage" on the main ...

OpenLayers: Issue with OSM visibility within div

I am facing an issue with loading the map content from OpenStreetMaps into a div within my hybrid mobile app. Here is the code snippet I am using: -JS: .controller('myCtrl', function($scope, $state, $ionicPopup, $cordovaGeolocation, Util) ...

Determining the current state of a CSS3 animation with jQuery

For example, I have this code snippet: @-webkit-keyframes anim { 0% { -webkit-transform: translate(-100px,0px) rotate(5deg); } 50% { -webkit-transform: translate(-140px,-5px) rotate(10deg); } 100% { -webki ...

Navigating through a predetermined list of HTML pages with next and previous options

Hey there, I'm in a bit of a quandary at the moment. I've been searching on Google for quite some time now, but unfortunately, I can't seem to find what I'm looking for. Hopefully, you guys can lend me a hand. What I'm trying to d ...

The user interface is presented with an array labeled as [object Object]

Currently working on a website using JavaScript, express.js, ejs, and Node.js and encountered a puzzling issue. The data is being sent to the frontend in the following manner: const dataToSend = [ { id: "ID", name: "Name" } ...

Enable the bottom footer to expand along with the content to support a dynamically growing page

I followed a tutorial on keeping footers at the bottom of a webpage (http://matthewjamestaylor.com/blog/keeping-footers-at-the-bottom-of-the-page) to create a site with a fixed footer. However, I encountered an issue when there is more content than can fit ...

The Facebook JavaScript API function FB.api() is limited to posting messages and does not support media attachments

I am attempting to share a message with an mp3 attachment on the active user's wall. It works perfectly fine within Facebook's Test Console, but when I try it from my mobile app, only the message gets posted. Can anyone help me figure out what I ...

Locking state object and properties as read-only in ReactJS/Typescript

I have an object from a third-party class and I want to ensure that its properties are read-only. This means that I do not want to be able to change the state with this.state.object.props = "xx"; The structure of the object is as follows: class ThirdPart ...

Instructions for turning an HTML table cell into an editable text box

Essentially, I'm looking to enable users to click on the table and edit the text within it. I found inspiration from this Js Fiddle: http://jsfiddle.net/ddd3nick/ExA3j/22/ Below is the code I've compiled based on the JS fiddle reference. I tho ...

problem with hiding bootstrap dropdown

Having trouble with Bootstrap, the dropdown menu is not hiding when I hover over the link. I want the dropdown to only show when I hover over it. Any help would be appreciated. Here is the code snippet: <nav> ...

When I hover over the button, the Fontawesome arrow will shift its position

.b_btnWrapp .btn.btn_default:after { content: "\f054"; font-family: 'Font Awesome 5 Free'; font-weight: 900; position: absolute; top: 15px; right: 30px; } .b_btnWrapp .btn.btn_default:after:hover { content: "\f054"; fon ...

Shifting text higher to the <h1> tag using CSS

I'm currently attempting to move the paragraph header closer to my h1 title. I'm struggling with incorporating the position function and have tried using padding without success. On the image, I am aiming to position the text "Where every connec ...