What is the best way to adjust text colors with a click of the mouse?

Is there a way to change the color of the text 'test' in the class 't1' when it is clicked on? I would like both texts to change color even if only one is clicked. The texts are separated by another div for design purposes.

I appreciate your assistance!

<script>

function change(div){
    if (div.style.color == "rgb(252, 198, 162)")
    {
        div.style.color="rgb(220, 20, 60)";
    }
    else
    {
        div.style.color="rgb(252, 198, 162)";
    }
}
</script>


<div class="t1" style="color: rgb(252,198,162);" onclick="change(this);">    
  <p>test</p>    
</div>    
<div class="t2" style="color: rgb(252, 198, 162);" onlcick="change(this);">    
  <p> test </p>    
</div>    
<div class="t1" style="color: rgb(252,198,162);" onclick="change(this);">    
  <p>test</p>    
</div>

Answer №1

This code snippet provides a straightforward solution using only vanilla JavaScript

function modifyColor(div) {

  var className = div.className; //retrieve the class name of the clicked element

  var elements = document.querySelectorAll("." + className); // get all elements with this class name
  elements.forEach(changeColor) // change color for each element

}

function changeColor(item) {
  if (item.style.color == "rgb(252, 198, 162)") {
    item.style.color = "rgb(220, 20, 60)";
  } else {
    item.style.color = "rgb(252, 198, 162)";
  }
}
<div class="t1" style="color: rgb(252,198,162);" onclick="modifyColor(this);">
  <p>test</p>
</div>
<div class="t2" style="color: rgb(252, 198, 162);" onlcick = "modifyColor(this);">
  <p> test </p>
</div>
<div class="t1" style="color: rgb(252,198,162);" onclick = "modifyColor(this);">
  <p>test</p>
</div>

Answer №2

To select all elements with the same class name, we can utilize the document.querySelectorAll method.

Below is a functional example using vanilla JavaScript:

function change(element){

var elementClassName = element.className;
var allElements = document.querySelectorAll('.' + elementClassName);

  for (var i = 0; i < allElements.length; i++) {

    var changeColorElement = allElements[i];

    // Implement your logic here
    if (changeColorElement.style.color == "rgb(252, 198, 162)") {
      changeColorElement.style.color="rgb(220, 20, 60)";
    } else {
      changeColorElement.style.color = "rgb(252, 198, 162)";
    }

  }

}
<div class="t1" style= "color: rgb(252,198,162);" onclick="change(this);">

<p>test</p>

</div>

<div class="t2" style="color: rgb(252, 198, 162);" onlcick="change(this);">

<p> test </p>

</div>

<div class="t1" style= "color: rgb(252,198,162);" onclick="change(this);">

<p>test</p>

</div>

Answer №3

Utilize a common class as suggested by brk to easily modify your code for the second time.

function adjustColor(div) 
{ 
if (div.style.color == "rgb(252, 198, 162)"){
$('.t1').css('color',"rgb(220, 20, 60)"); 
} 
else {
$('.t1').css('color', "rgb(252, 198, 162)");
}

excluding p tag

Answer №4

<!DOCTYPE html>
<html>
<body>

<div class="t1" style="color: rgb(252,198,162);" onclick="updateColor(this);">    
  <p>sample text</p>    
</div>    
<div class="t2" style="color: rgb(252, 198, 162);" onclick="updateColor(this);">    
  <p> test example </p>    
</div>    
<div class="t1" style="color: rgb(252,198,162);" onclick="updateColor(this);">    
  <p>testing color</p>    
</div>


<script>
function updateColor(e){
var elements = document.querySelectorAll("."+e.className);
if (typeof elements !== "undefined") {

for (var i = 0; i < elements.length; i++) {
    if(elements[i].style.color == "rgb(252, 198, 162)")
    {
    elements[i].style.color="rgb(220, 20, 60)";
    }
    else
    {
    elements[i].style.color="rgb(252, 198, 162)";
    }
}
}
}
</script>

</body>
</html>

Provides assistance.

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

Transformation of a double-row header

Click here to view the design - two-row header image I'm struggling with creating a header design that consists of two rows - the first row includes a centered logo and icons on the right side, while the second row contains the menu. Can someone guid ...

Proxy/firewall causing interference with socket connection from chrome extension

I have encountered an issue with my web app in JavaScript that connects to a socket using socket.io and a Chrome Extension that also connects in the same way to the same server. While everything works smoothly on most computers and internet connections, th ...

How do I modify the sidebar width with CSS code?

I am trying to adjust the width of the right sidebar on my website. The current layout leaves too much empty space on the right side and makes it appear crowded next to the main content and images in the center. Despite exploring various solutions provide ...

Generate a list of users using Angular in an efficient manner

I am working on creating a user list similar to the image provided below. I am using Angular and Bootstrap for the basics of this project. However, my concern is how to efficiently handle a large number of users. If the user count exceeds 10k, what would b ...

Iterating through a nested array of objects to merge and accumulate values

Just started learning Javascript. I've been trying to wrap my head around it for hours, looking at examples, but still struggling. I'm working with an array of objects that have nested properties which I need to loop through and consolidate. ...

Executing Javascript code from a specified web address

Let's say I have an image that needs to be shifted vertically, and I achieve it using the following code snippet: document.getElementById('ImgID1').style.verticalAlign = However, the value by which I need to shift the image is provided thr ...

Navigating with Angular JS - Efficient Routing

I am currently utilizing the MEAN framework along with express routing requests. My application has two primary routes - public/ and app. The "app" route serves as an API, while the "public" route consists of web pages that display data fetched from the A ...

"Adjusting the height of Material UI card content to ensure fixed positioning at the bottom

Currently, I am working on mapping material-ui cards with dynamic content from a JSON object, resulting in varying card heights. I have successfully set a fixed height for each card, but the content is not aligned correctly. You can see the issue in this ...

Please provide clear guidance on the learnyounode assignment number 6 focused on "MAKE IT MODULAR."

I'm struggling to understand the instructions provided for this exercise. I find it difficult to differentiate between which file is considered the module and which one is referred to as the "original program file." I can comprehend the solutions give ...

Tips for keeping a div stationary when an adjacent div expands

I am facing an issue with 3 blocks in a row - a large block, a smaller block that can expand, and a third block placed under the first block. When the smaller block expands, the top of the third block moves to match the bottom of the expanding div. However ...

Troubleshooting Angular 5: Interceptor Fails to Intercept Requests

I have a valid JWT token stored in local storage and an interceptor that I borrowed from a tutorial. However, the interceptor is not intercepting requests and adding headers as expected. Here's where I am making a request: https://github.com/Marred/ ...

Formatting the numbers for an unordered list located outside of the content

Can the numbers of an ordered list be formatted using the list-position-style set to outside? I am looking for a solution using only CSS since I cannot edit the HTML. Essentially, I want styled numbers with round background to replace the outside numbers. ...

Unable to modify the background image of the button

Currently, I am working on this element I am trying to insert a background image into the "Click" button, but I am not seeing any results. Here is the HTML and CSS I am using: .cn-button { position: absolute; top: 100%; left: 50%; z-ind ...

Develop a smartphone app for a online platform

I am currently in the process of developing an asp.net jQuery mobile web application that is mobile responsive. I now have a need to create a basic mobile app that can be easily installed on mobile devices, simply functioning as a wrapper that will display ...

Backbone.js experiencing synchronization issues exclusively in Internet Explorer

Can anyone confirm if they have encountered this issue before? I'm unsure how to elaborate further as it seems to be the only symptom. Additionally, it does not sync correctly in Internet Explorer. ...

Angular 2 Rapid Launch: Incorrect Encoding of JavaScript Files

I am brand new to learning angular 2, so I am currently attempting to get things up and running following this guide: https://angular.io/guide/quickstart The issue I am facing has left me quite puzzled. Whenever I receive any JS files as a response, they ...

What could be the issue with my injection supplier?

When running the following code, the configuration works fine, but an error is returned: Uncaught Error: [$injector:unpr] Unknown provider: AngularyticsConsoleHandlerProvider <- AngularyticsConsoleHandler <- Angularytics Code snippet: angular.modu ...

What is the process for indicating a specific spot on Google Maps?

Hello, I am a new programmer trying to indicate the location of my company. The map pointer is not showing up even though the location is correct. I have tried numerous solutions but none seem to be working. Any assistance would be gre ...

What is the best way to maintain the highlighting of a clicked navigation button in CSS?

.custom-highlight { display: inline; font-weight: 500; font-size: 15px; } .item-list { border: 1px solid #b1b8c9; color: $color-grey-light; font-size: 14px; display: inline-block; margin-right: 8px; padding: 5px 20px; border-radius: 4p ...

Ways to retrieve several URLs from a given text

Here is a string containing three URLs: "https://gaana.com/song/dil-chahte-hohttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APmhttps://www.youtube.com/watch?v=MWnFCGXjjS0&list=PLs1-UdHIwbo5p-8wh740E7CRhIoKq5APm ...