Apply a unique design to a class by clicking on a button

There are 3 identical boxes with the same classes and a button:

function changeColorAndAddPadding() {
  /* ??? */
}
.box {
  border: 1px solid;
  display: inline;
}
<button onclick="changeColorAndAddPadding();">Click Here</button>

<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>

I am looking to apply styles to the class .box when the button is clicked, without adding a new class to the boxes. Essentially, upon clicking the button, I want the .box class to have a red background color and padding, which should also be applied to all elements with this class. Is there an efficient way in JavaScript to achieve this?

Thank you in advance.

Answer №1

If you're looking to enhance the styling of elements without modifying the existing class, consider creating a new class that includes the desired properties in each element's class list.

Guidance

  1. To target specific elements for manipulation, utilize querySelectorAll for a static nodelist. This method is preferable over live HTML collections like getElementsByClassName.

  2. Iterate through the selected elements using iteration techniques. Consider employing forEach for efficient processing.

  3. To update each element's class list during iteration, leverage the classList interface and its add method to append CSS classes.

  4. Define a separate class (e.g., "redpad") to encapsulate the styles needed.

  5. Incorporate event delegation by utilizing addEventListener with specified event types and corresponding functions to ensure clean separation of concerns.

const button = document.querySelector('button');
const boxes = document.querySelectorAll('.box');

button.addEventListener('click', turnRedAndAddPadding);

function turnRedAndAddPadding() {
  boxes.forEach(box => {
    box.classList.add('redpad');
  });
}
.box {
  border: 1px solid;
  display: inline;
}

.redpad {
  background-color: red;
  padding: 0.5em;
}
<button type="button">Press</button>

<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>

Answer №2

Referring to this particular post, you may want to experiment with the following code snippet:

function turnRedAndAddPadding() {
  stylesheet = document.styleSheets[0]
  stylesheet.insertRule(".box { background-color: red; padding: 10px;}", 0);
}
.box {
  border: 1px solid;
  display: inline;
}
<button onclick="turnRedAndAddPadding();">Click here</button>

<div class="box">Box A</div>
<div class="box">Box B</div>
<div class="box">Box C</div>

I hope this suggestion proves useful.

Answer №3

W3 Schools provides valuable documentation on utilizing the getElementsByClassName method, which can be accessed here. Information on adjusting padding can also be found here, using the padding property of each element.

In the following code snippet, I am targeting all divs with the class "box". By looping through each one, I am setting the color and padding dynamically. Feel free to customize this according to your preferences.

Additionally, there are plenty of other properties that you can modify for each DOM element, including divs!

function turnRedAndAddPadding() {
  const collection = document.getElementsByClassName('box');

  for (let i = 0; i < collection.length; i++) {
    collection[i].style.backgroundColor = 'red';
    collection[i].style.padding = '5px';
  }
}

Answer №4

By incorporating some javascript code, your objective can be accomplished successfully.

Utilize document.querySelectorAll to gather all elements that have the class box, then proceed by iterating through them with a foreach loop.

function turnRedAndAddPadding() {
  let box = document.querySelectorAll('.box');
  box.forEach(el => {
    el.style.background = 'red';
    el.style.padding = '20px'
  })
}
.box {
  border: 1px solid;
  display: inline;
}
<button onclick="turnRedAndAddPadding()">Press</button>

<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</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

The CSS media query isn't functioning properly on Safari browser

Currently, I am working on a project using React JS and CSS. In order to make it responsive, I have implemented media queries. However, I have encountered an issue where the media query is not functioning properly in Safari browsers on both phones and PC ...

Is anyone else experiencing issues with the Express middleware that checks for IDs? Looking for suggestions on how to fix

Currently working on a project with Node js utilizing Express and MongoDb for the backend. In this project, USERS have the ability to post COMMENTS, so I have created a middleware to access the DELETE route and check if the USER ID matches the ID of the in ...

Caution: Anticipated the server's HTML to include a corresponding <body> within a <div> tag

Upon checking the console, I noticed a warning message appearing. I am puzzled as to why this is happening since I have two matching <body> tags in my index.js file. The complete warning message reads: Warning: Expected server HTML to contain a matc ...

Parsing a Table in Python with HTMLParser

I am trying to convert an HTML table into a 2D array (rows and columns) using only the HTMLParser library in Python, without relying on BeautifulSoup or other non-standard libraries. This task is part of a personal project that I am working on for fun :) ...

JS Data error: The attributes provided must include the property indicated by idAttribute - particularly with regards to hasMany relationships

Encountered Error: The main key for my user model is username. The primary key for my routes is the routename. When my API returns JSONs, they are nested inside data:{} following jsonapi.org specifications. However, this structure differs from what js-dat ...

The caching mechanism in IE 11 is preventing Ajax from loading and displaying data

Utilizing Ajax to verify data and display it on the page, alongside implementing varnish cache. The data appears correctly on all web browsers, with the exception of IE 11, unless the varnish cache is disabled. function checkMyData() { var surl = 'in ...

I'm curious if anyone has had success utilizing react-testing-library to effectively test change events on a draftJS Editor component

​I'm having trouble with the fireEvent.change() method. When I try to use it, I get an error saying there are no setters on the element. After that, I attempted using aria selectors instead. const DraftEditor = getByRole('textbox') Draf ...

Modify the width of the progress bar in Bootstrap using AngularJS

I'm new to AngularJS and I'm attempting to dynamically update the width of a progress bar based on changes in my controller. Here is what I currently have: <span id="percentage">$ {{getTotal()}} ({{getPercentage()}}%)</span> <div ...

Encountered an error while trying to install @material-ui/core through npm: Received an unexpected end of JSON input

npm install @material-ui/core npm ERR! Unexpected end of JSON input while parsing near '...X1F+dSMvv9bUwJSg+lOUX' npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\WR-022\AppData\Roaming\npm-cach ...

What could be the reason for the clone function not duplicating the data within the table

Recently, I utilized jQuery's clone method to duplicate and add an HTML table. The rows and cells of the table were added using jQuery. However, despite using clone, it only replicated the headers and CSS, not the appended data. This raises the ques ...

Transform CSV data into JSON format to generate an empty JSON file

I've been attempting to convert a CSV file to JSON using the convert-csv-to-json package from npm. Although I can successfully retrieve the CSV file from the specified URL and create a 'data.csv' file, the resulting JSON file is only an empt ...

Arranging DIVs in a vertical layout

Currently, I am working on a design that involves organizing several <DIV> elements in a vertical manner while still maintaining responsiveness. Here are some examples: Wider layout Taller layout I have tried using floats, inline-block display, ...

Test your word skills with the Jumbled Words Game. Receive an alert when

After reviewing the code for a jumble word game, I noticed that it checks each alphabet individually and locks it if correct. However, I would like to modify it so that the entire word is only locked if all the letters are correct. Any suggestions on how t ...

When you press multiple buttons, the correct button will reveal an image while the incorrect buttons will display an X

Could you lend a hand with the code below? Your assistance is truly appreciated :). Thank you in advance. I need help setting up a functionality where clicking on the correct button (e.g. H) will display a checkmark and a forward link image. If the user c ...

select specific region within image

I'm currently working on cropping an image and sending the cropped data to the server side. To achieve this, I am utilizing the imgareaselect plugin. While I am able to obtain the coordinates of the selection, I am facing challenges in actually croppi ...

Alerts for drop down menu validation with multiple buttons

My goal is to design a multi-step form that collects user information. This form consists of 5 stages: Step 1: User details (Name, email, phone, age, gender) Step 2: Yes or No question Step 3: Yes or No question Step 4: Yes or No question Step 5: Yes o ...

Having trouble combining different styles with Material-ui and Radium?

Trying to integrate Radium with Material-ui has presented a challenge. Attempting to apply multiple styles to a single Material-ui component results in no styling being applied. For instance, the following code fails to render any styling: <MenuItem st ...

How to format values in a textarea using AngularJS

Is there a way to address the following issue without replacing \n with other values? A user can input a description for something in a textarea and include line breaks. In the controller, there is a value called description which includes a string ...

How to eliminate margins in Django's easy_pdf module

For generating PDF from HTML, I utilize easy_pdf in conjunction with xhtml2pdf. Below is a brief example: In view.py from easy_pdf.rendering import render_to_pdf_response context = dict({'user_company': 'test'}) template_name = "pdf ...

Using Selenium with JavaScript and Python to simulate key presses

Is there a way to simulate key presses as if typing on a keyboard? I am looking to programmatically click on an input element and then emulate the user typing by pressing keys. I prefer not to use XPath selectors combined with sendkeys or similar methods. ...