Struggling with updating the background color of multiple HTML elements with the same class in real-time

I'm facing an issue with dynamically updating background colors of specific elements using ajax, JSP, and a servlet call. Even though all the lines of code seem to be executing, there is no visible change on the front end. I've attached my JS functions along with a screenshot showing the servlet and console log. Any assistance would be highly appreciated! I also attempted to create another JS function to handle the background changes, but unfortunately, that didn't resolve the problem.

        <script>
         function validate() {
                 console.log("hello");
              var xhttp = new XMLHttpRequest();
              xhttp.open("GET", "/"+window.location.pathname.split("/")[1]+"/HomeServlet?inputName=" + document.searchform.search.value, false);
              xhttp.send();
              if (xhttp.responseText.trim().length > 0) {
                    console.log("in if statement " + xhttp.responseText);
                    var str = xhttp.responseText;
                    var result = str.split(" ");
                    console.log("str " + str + " - result: " + result + " result size = " + result.length);
                    for(var i = 0; i < result.length; i++) {
                        console.log("in first loop");
                        console.log("value:" + result[i]);
                        elements = document.getElementsByClassName(result[i]);
                        console.log("elements: " + elements.length);
                        for (var j = 0; j < elements.length; j++) {
                            console.log("in the loop");
                            //elements[j].style.backgroundColor = "red";
                            changeBg(elements[j]);
                        }
                    } 
                //return false;
              }
              return true;
          }
         function changeBg(element) {
                alert(window.getComputedStyle(element).backgroundColor);
                element.style.color = "red";

            }
        </script>

The console output in my browser confirms that each line of code is being executed, including displaying the alert box, but for some reason, the element.style.color or backgroundColor is not changing as expected despite trying both approaches.

Answer โ„–1

Kindly utilize

element.style.backgroundColor

as opposed to

element.style.color

since style.color is intended for modifying font color, not background color

Answer โ„–2

I believe the most effective solution would be to introduce new color styles for the existing classes.

var counter = 0;
function changeBackground(){
counter++;
var css = '.testBGclasss { background: '+(counter%2?'red':'blue')+'; }',
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');

style.type = 'text/css';
if (style.styleSheet){
  style.styleSheet.cssText = css;
} else {
  style.appendChild(document.createTextNode(css));
}

head.appendChild(style);
}
<html>
<head></head>
<body>
<div class="testBGclasss">
<h1>Some text<h1>
</div>
<input type="button" value="change background" onclick="changeBackground()"/>
</body>
</html>

Answer โ„–3

Appreciate the assistance. I managed to solve it on my own. It appears that maintaining dynamic changes in certain parts of a form is not possible.

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

What is the easiest way to include a copyright symbol in a React component?

I am trying to include the copyright symbol in a React component, but it doesn't seem to be working for me. function Footer() { return ( <footer> <p>&copy</p> </footer> ); } <p>&copy</p> ...

Is there a way to adjust the transparency of specific text when clicking on a different div?

How can I display a line of text when the "Contact Us" button is clicked on a practice website, similar to this: https://i.sstatic.net/MgbYQ.png I have set the current opacity of the submit message to 0 so it is hidden, but is there a way to change its o ...

What is the best way to incorporate a text box along with a submit button that triggers a callback to a javascript function when clicked, utilizing either plain javascript or jQuery?

As a beginner in the world of JavaScript, I'm struggling to find the solution to this problem. Any assistance would be greatly welcomed. ...

Encountering an unusual error while utilizing the Rails 3 form_for with the :remote option set to true

Encountering an error and seeking assistance: try { Element.update("status", "There seems to be an issue with this product."); } catch (e) { alert('RJS error:\n\n' + e.toString()); alert('Element.update(\"status\", &bsol ...

Angular does not seem to be identifying the project name as a valid property

After installing Angular materials using the CLI, I decided to check my angular.json file and encountered an error in the console stating that "Property MEAN-APP is not allowed". [The name of my Angular project is MEAN-APP] Here's a screenshot of the ...

Listen for an event on a button to show a specific div

Looking to have a div appear when the user clicks on a button. //html-code <div class="col-md-4"> <h4 class="service-heading">Social Media</h4> <p class="text-muted">This is the first line of text.</p& ...

What could be causing the misalignment of divs with margins?

I'm facing an issue where I can't seem to get two h2 elements with top margin set and placed inside divs floating left to line up properly. Any help would be appreciated. <html> <head></head> <style> h2{ ...

Comparing the use of visibility: hidden with -webkit-transform: translate3d() within a PhoneGap application

Currently, I am creating a hybrid application using PhoneGap. As part of the design, I have several divs (each representing a page) that I toggle between by changing their visibility in CSS using "visibility: hidden" and "visible". However, I recently ca ...

Error occurred while attempting to access querystring values

Is there a reason why 2 out of the 3 querystring parameters have values, while one is undefined? <li class="@ViewBag.ShowNext">@Html.RouteLink("Next ยป", "Search", new { page = @ViewBag.NextPage, q = @ViewBag.TextClean, Option = @ViewBag.Option }, n ...

Solving Mixed Content Issues in JavaScript

I'm attempting to retrieve information from OMDB API, but I'm encountering an issue with mixed content images. OMDB pulls its data from IMDB, which does not allow the use of https images. Therefore, all image sources must be prefixed with http. ...

Tips for eliminating the gap between Bootstrap 4 columns

Is there a way to eliminate the spacing between Bootstrap columns? I have three columns set up using Bootstrap but no matter what I do, I can't seem to get rid of the space between them. <!doctype html> <html lang="en> <head> ...

What steps can be taken to enable users to draw a path on a Google Map?

I'm working on a new project for a Facebook app that will allow users to map out their marathon route using Google Maps. I plan to utilize mySQL database records to store fixed points along the path (such as specific locations based on latitude and lo ...

Hapi/Node.js Reference Error for Request: Troubleshooting the Issue

I am facing an issue with my two API handlers: module.exports.loginWeb = function (request, reply, next) { if (request.auth.isAuthenticated) { return reply.redirect('/'); } if(request.method === 'get'){ rep ...

Designing a slider to display a collection of images

I am currently working on a slider project using HTML, javascript, and CSS. I'm facing an issue where only the first two images (li) are being displayed and it's not transitioning to the other (li) elements. Below is the HTML code snippet: <se ...

Storing dropdown values in variables using AJAX and JQuery

In my code snippet, I have the following:- <script> $("#country").on("change", function(){ var selected = $(this).val(); $("#results").html("<div class='alert-box success'><span><img src='images/ ...

Tips for updating the data value of a specific block using Vue.js

I am looking to develop a basic Vue.js application. Within this app, I have multiple counter blocks that are rendered using the v-for directive. In my data object, I initialize a 'counter: 0' instance. My goal is to increment and decrement only o ...

How to Conceal the Search Bar in jQuery DataTables

I am having trouble hiding the default search bar in DataTables. Despite trying solutions from this thread, using bFilter:false completely disables filtering, rendering my search boxes in the footer non-functional. I have created a jsfiddle demonstration. ...

Passing an array from PHP to JavaScript using AJAX

Here is the code snippet on the server side: <?php header('Content-Type: text/html; charset=utf-8'); require "../general.variables.php"; require "../functions_validation.php"; require "../functions_general.php"; require "../../db_con.php"; $ ...

Printing a database value in CKEditor using the select option method

Hello everyone, I'm new to PHP and have a question. I created a select option using a MySQL script with five values. Every time I change the select option value, the appropriate result is displayed. However, the values are not displayed in the CKEdito ...

Designing an intricate layout with the help of Bootstrap-Vue

After exploring the Vue-Bootstrap panel in my previous question, I implemented the following code snippet to generate a panel: <b-card no-body class="mb-1"> <b-card-header header-tag="header" class="p-1" role="tab"> <b-button b ...