JavaScript for Color Swapping on Click Event

While working on coding a website, I attempted to change colors and pictures onclick using JavaScript to edit the CSS. However, the code is only partially functional. Only the "txtArea" field changes color. After checking validators and consoles, everything seems to be syntactically correct.

<!-- This button triggers the color change. -->
<div id="colorSelector"><span id="chngBlue"><a href="#" onclick="chngColor()">&bull;</a></span> &bull; &bull;</div>

<script>
var colors = ["#0099cc", "#669900", "#993333"];//Blue, Green, Red

function chngColor(){
document.getElementById("txtArea").style.backgroundColor = colors[2];
document.getElementsByClassName("labHdr")[0].style.backgroundColor = colors[2]; 
document.getElementById("newLink").style.color = colors[2];
document.getElementById("hdBanner").src='bannerred.png';
}
</script>

Answer №1

When using document.getElementsByClassName("labHdr"), you will receive an HTMLCollection as a return value (credit to @Teemu for the clarification). This collection does not have a 'style' property by default. To apply styles to elements within this collection, you can utilize the following code snippet:

var myElements = document.getElementsByClassName("labHdr");

for (var i = 0; i < myElements.length; i++) {
    myElements[i].style.color = colors[2];
}

Answer №2

The method getElementsByClassName will give back an object that looks like an array, so remember to access it with an index even if there is only one element inside.

Therefore, the second line of the function should now be:

document.getElementsByClassName("labHdr")[0].style.backgroundColor = colors[2];

http://codepen.io/markwill/pen/rrAXzr

If there are multiple elements with this class, you will need to loop through each one and set the desired style (it's better to do this than assuming there is only one).

Answer №3

Modify:

function chngColor(){
    document.getElementById("txtArea").style.backgroundColor = colors[2];
    document.getElementsByClassName("labHdr").style.backgroundColor = colors[2];
    document.getElementById("newLink").style.color = colors[2];
    document.getElementById("hdBanner").src='bannerred.png';
}

To this:

function chngColor(){
    var labelList = document.querySelectorAll(".labHdr");
    document.getElementById("txtArea").style.backgroundColor = colors[2];
    document.getElementById("newLink").style.color = colors[2];
    document.getElementById("hdBanner").src='bannerred.png';

    Array.prototype.map.call(labelList, function(element) { 
        element.style.backgroundColor = colors[2]; 
    });

}

This change will update all your labels.

Answer №4

To change the color of an element, you can use the getElementById method as shown in the example below:

<h1 id="id1">My Heading 1</h1>
<button type="button" 
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>

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

Issue with margin-top in combination with clear:both does not function as expected

<div style="float: left;">Left</div> <div style="float: right;">Right</div> <div style="clear: both; margin-top: 200px;">Main Data</div> What is causing the margin-top property to not work as expected for 'Main Dat ...

Adjust the canvas size to perfectly fit within the parent bootstrap cell in a grid layout

I am currently in the process of creating a dashboard using the Bootstrap grid. Some of the cells contain a canvas element, and I am trying to ensure that it matches the size of its parent. My approach involves the following calculations: var parent = can ...

Executing a callback in Node.js after a loop is complete

As a newcomer to Node, I have been facing difficulties with the asynchronous nature of the platform while attempting to append data in a for loop of API calls. function emotionsAPI(data, next){ for(let url in data) { if(data.hasOwnProperty(url ...

Encountering the error message "Undefined variable '$'" in a script that is loaded after jQuery

My code is simple - it loads jQuery first, followed by a script that uses the $ syntax. However, I keep encountering the error: ReferenceError: $ is not defined Initially, I suspected that the async attribute on the script tag was the issue, but changi ...

the table image does not resize correctly in mobile view

I need to resize an image inside a table's <td> when the screen size is in mobile mode. Although I have already added a viewport, my mobile query works correctly for other purposes except for the image. Here is the HTML code: <table class="t ...

The error message that you are seeing is indicating that the `contracts` property of `this.state

Despite having encountered this issue before, I am still struggling to find a solution. The code snippet for fetching data is as follows: async componentDidMount(){ try { const res = await fetch('https://example.com/data.json'); ...

Receive characteristics in component specification

Is there a way to pass the native attributes of an img element to a custom image component without explicitly defining each one, like alt, and have them all be applied to the img tag? Here is an example of what I mean: @Component({ selector: 'image ...

Obtain variable declared in script tag (Google Chrome Extension)

I'm facing a dilemma. I need to retrieve the value of a variable defined inside a script tag in the DOM. <script id="foo"> var x = 1 </script> I tried accessing it like this: var script = document.querySelector("#foo"); But what ne ...

How can I effectively implement a withAuth higher order component (HOC) in TypeScript within Next.js?

Currently, I am working on a Next.js application and implementing the next-auth package. My goal is to develop a Higher Order Component (HOC) that can determine if the component has an active session or not. Along with this, I am utilizing eslint for code ...

How to Use PHP to Submit Form Information

I am a beginner in PHP and I need help with sending form details to an email address. I have tried looking for solutions online but I keep running into the same issue - when I submit the form, it downloads the PHP file instead of sending an email. Below i ...

Push-grid interaction through drag-and-drop feature

I'm on a quest to incorporate grid drag-and-drop functionality into my project. While there are numerous frameworks available that offer this feature, one of the most popular options is JQuery UI's sortable library. However, I am specifically lo ...

Ways to extract the id after clicking

In my code, I have a query called snapshot.forEach that functions similarly to a for loop in looping through all of my Firebase data and displaying it with a div tag containing a click event. When another user clicks on this div tag, the event will retriev ...

Adding a custom validation function to the joi.any() method - the easy way!

Is there a way to enhance joi.any() with a new rule that can be applied to any existing type, such as joi.boolean() or joi.string()? I already know how to extend joi by creating a custom type but that doesn't allow me to combine the new type with exis ...

Combining images with PHP

I have a collection of numerous images that are all the same size in terms of width and height. In total, there are over 50 unique images. My goal is to combine these images along both the horizontal (X) and vertical (Y) axes. Specifically, I would like ...

Guide to organizing an express.js project structure:

When working with an Express.js application, what are the typical strategies for breaking up and modularizing the app.js file? Do developers usually keep everything in a single file, or is there a common convention for splitting it into smaller modules? ...

Tips for Removing Scrollbars on Mobile Devices

Currently, I have implemented -webkit-scrollbar{ display:none; } on my website, and it functions well on desktop devices. However, upon inspecting on Chrome devtools for mobile devices, the scrollbar still appears. Initially, the scrollbar does not seem ...

difficulty in obtaining information submitted through a form

I'm having an issue with my contact form. I tried testing to see if I can retrieve the values from the form, but it's giving me back: name: undefined I'm not sure why it's not working! Here is the code for the form: <form met ...

Disable the height property in the DOM when implementing the jQueryUI resizable feature

I'm utilizing the flex property to create a responsive layout for my web application. In order to enable resizing of my navigator panel, I have implemented jQuery UI. However, upon triggering the resize event, jQuery UI is adding a hardcoded height t ...

Having trouble with the placement of my footer div - seeking a solution

I've been trying to center my footer, but it keeps aligning to the left. Here's a screenshot for reference Below is the code I'm working with (core.blade.php): <div class="footer"> <div class="row align-self-end& ...

Shapes in Three.js with multiple colors

As a newcomer to Three.js and webGL programming, I have successfully created a cone and a cylinder in my scene using the script provided below: var scene; var camera; var renderer; var createACone = function() { // Cone creation code here } var creat ...