Modify the colors of multiple texts using a concise code block of fewer than 20 lines

I have 8 paragraphs and I want to toggle the class 'one-active' when clicking on each of them, while removing the active class from the others. I currently have the code working for two paragraphs, but it's too lengthy for all eight. How can I achieve the same functionality with fewer lines of code?


      let paragraphs = document.querySelectorAll('p');
  
      function changeColor(index){
        paragraphs.forEach((p, i) => {
          if(i === index){
            p.classList.toggle('active');
          } else {
            p.classList.remove('active');
          }
        });
      }
  
      paragraphs.forEach((p, i) => {
        p.addEventListener('click', () => {
          changeColor(i);
        });
      });
    

      <style>
        p{
          color: rgb(11, 28, 47);
          background-color: rgb(255, 255, 255);
        }
        
        p.active{
          color: rgb(255, 255, 255);
          background-color: rgb(11, 28, 47);
        }
      </style>
      
      <p>COSA È</p>
      <p>COSA È</p>
      <p>COSA È</p>
      <p>COSA È</p>
      <p>COSA È</p>
    

Answer №1

Instead of creating a separate class for each p element, you can use a single CSS rule to indicate that an item is active. Also, rather than having a click handler for each individual element, you can set up a click handler on the parent element to manage activation and deactivation.

let container = document.querySelector(".container");

container.addEventListener("click", ({
  target
}) => {
  if (target.nodeName !== "P") return; // return if p is not clicked
  Array.from(document.querySelectorAll(".container>p")).forEach(p => p.classList.remove("active")); // make the others inactive
  target.classList.toggle("active");
});
.container p {
  color: rgb(11, 28, 47);
  background-color: rgb(255, 255, 2);
}

.container p.active {
  color: rgb(255, 255, 255);
  background-color: rgb(11, 28, 47) !important;
}
<div class="container">
  <p class="active">COSA È</p>
  <p>COSA È</p>
  <p>COSA È</p>
  <p>COSA È</p>
  <p>COSA È</p>
</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

Understanding information in Backbone.js

I have multiple backbone models with nested sub-models. Here's how I've approached the solution: Models.Base = Backbone.Model.extend ({ relatedModels: {}, /** * Parses data based on the list of related models. * * @since ...

Associate an alternate attribute that is not displayed in the HTML component

Imagine there is a collection of objects like - var options = [{ id: "1", name: "option1" }, { id: "2", name: "option2" } ]; The following code snippet is used to search through the list of options and assign the selected option to anot ...

What could be the reason behind these links not affecting the height of my div element?

I am having trouble with the links not changing the height of the "holder" element. I can't seem to figure out what is going wrong. HTML: <div id="holder"> <a class="button" href="#"><span>home</span></a> <a class="b ...

Obtain the href using a combination of xpath and id

I need to extract the href links for 9 search results from this specific website. The xpath and selectors for the first, second, and third items are as follows: '//*[@id="search-results"]/div[4]/div/ctl:cache/div[3]/div[1]/div/div[2]/div[2]/div[2]/p[ ...

The $resources headers have not been updated

My objective is to include a header with each HTTP request for an ngResource (specifically, an auth token). This solution somewhat accomplishes that: app.factory('User', ['$resource','$window', function($resource,$window,l ...

Host an Angular app with views using Express.js - reloading is disabled

I'm currently working with an expressjs configuration that looks like this: app.use(express.static(path.join(__dirname,"../../site"))); app.use("/src", express.static(path.join(__dirname,"../cms/src"))); app.get('/', function(req, res){ ...

Utilizing Fullcalendar v5's sticky header feature alongside a Bootstrap fixed top navigation bar for a seamless

Currently experimenting with the latest version of fullcalendar 5.4.0. I have integrated the calendar into a bootstrap 4 web page that features a fixed navigation bar at the top. The issue arises when attempting to set stickyHeaderDates, aiming to keep th ...

It is not possible to include a new property to an object while inside a function

Looking to add a property to an object? Check out the code below: import React from 'react'; import { Link } from 'react-router-dom'; const Question = () => { let active; const handleClick = (iconName) => { active = {}; ...

When using Angular 5's ngModel, the user interface displays the updated value dynamically without requiring the

When filling out my form, I encounter an issue with a select element and a bind variable. If I make a change to the value and save it, everything works as expected. However, if I make a change in a modal window but then close the modal without saving the v ...

Attempted to identify whether an item exists in an array, and if it does, then add the item to the array; if not, then perform

Allow me to make some clarifications as it might be a bit confusing initially. This project I'm working on is for school. I don't expect anyone to do it for me, but I need help with a specific part. I'm creating a simple shopping cart using ...

Facing an error response with the Javascript callout policy in Apigee. Any suggestions on fixing this issue?

This is the code snippet I'm using in my JavaScript callout policy var payload = JSON.parse(request.content); var headers = {'Content-Type' : 'application/json'}; var url = 'https://jsonplaceholder.typicode.com/posts'; va ...

Set an attribute without replacing any existing class attributes

I have developed a script that updates the class attribute of the body element on my website when an option is selected from a dropdown menu. However, I am facing an issue where it overrides the existing dark mode attribute. The purpose of this script is ...

"Triggering an event when a checkbox in a list is clicked

How can I add an onclick event to a checkbox within an <li> element, as shown in the picture? Here is my JavaScript code so far: It's not working. $(document).ready(function() { allFiles() /*----------------------------------------------- ...

Express.js and Node version 0.10.29: The Mystery Post

Having trouble with sending JSON data to an express server and receiving 'undefined' for req.body.name. This is how the configuration is set up: const express = require('express'); const app = express(); app.configure(function(){ ...

Using React.js to add MongoDB documents into the database

Is there a way to directly insert documents into a MongoDB collection from a React component? I have been working on a personal project, which is a chat web application used for training purposes. For instance, when a user wants to post a new message in a ...

What is the method for retrieving JSON data within the AngularJS repeat directive?

I am seeking guidance on how to retrieve the main menu and sub menus separately from a JSON file using ng-repeat. Here are the relevant files: menu.json {"data": { "main menu": { "menu1": [ ...

Manually validate inputs in Angular

I've encountered an issue with the bootstrap datepicker. When I click on the date icon, the date and time automatically populate in the input field. However, the input remains invalid because I haven't directly interacted with it. Has anyone else ...

Guide to creating a distortion-free layout with Bootstrap 4

I am in need of creating a design layout using Bootstrap 4 with the following specifications: https://i.sstatic.net/JeUHh.png Here is my code : <div class="row"> <div class="col-md-7"> A </div> <div class="col-md-5"> <div ...

Maintaining the position of the screen as you type in information that is located outside of the container

I am encountering an issue with the input/text-area element in absolute position extending halfway outside the container. The screen position seems to follow the caret as I type, but I'd prefer to keep writing and have part of the text hidden beyond t ...

What is the best way to combine MVVM, offline storage, and Knockout.js in a project?

Although I have experience with implementing Mvvm using Knockout.js, my goal now is to incorporate this framework with cross-browser support for Firefox and Chrome along with HTML5 offline storage capabilities. Specifically, I am looking to bind HTML obje ...