Is it possible to alter the background color of numerous strings based on their inclusion of a specific word?

My goal is to determine if a group of strings contain a specific word, and based on that, change the background color. If any member within the group has the word 'unlikely', I want the background color to be green; otherwise, it should be red. The desired outcome is to have some members with green backgrounds and others with red backgrounds.

Unfortunately, my code is not functioning as expected.

This is what I've attempted:

function colorCoding() {
    var str = document.getElementsByClassName("colorString").innerHTML;
    var n = str.includes("unlikely");
    if (n == true) {
      document.getElementById("colorString").style.backgroundColor = "green";
    } else {
      document.getElementById("colorString").style.backgroundColor = "red";
    }
}

However, the background color remains unchanged despite running the above code.

I did manage to get it to work for individual IDs, but doing so for each member of the class would be time-consuming. Is there a way to achieve this using the class or perhaps by modifying the function to apply to the entire set?

Any assistance you can provide would be greatly appreciated!

Answer №1

The issue lies within the code snippet

document.getElementsByClassName("colorString").innerHTML
. Don't forget to specify the index position in order to access the desired element, as demonstrated here:
document.getElementsByClassName("colorString")[0].innerHTML
.

The method

document.getElementsByClassName()
retrieves an array of elements sharing the specified class name.

To iterate through the elements, you can use a for loop like this:

 var i;

 var items = document.getElementsByClassName("colorString");
 for (i = 0; i < items.length; i++) {

    if(items[i].innerHTML.includes("unlikely")) { 
      items[i].style.backgroundColor = "green";
  } else {
  items[i].style.backgroundColor = "red";
}

 }

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

Utilize the splice function when resizing the window based on specific breakpoints

On a series of div elements, I have implemented some JS/jQuery code that organizes them by wrapping every three elements in a container with the class .each-row. <div class="element"></div> <div class="element"></div> <div class ...

The failover process for PayPal involves seamless transitions to backup systems in the

I am currently assisting a client with a unique architecture setup: Back End Running on Java Server Front End Powered by Proxy (Node JS + Express application) For security reasons, all requests made to the server must pass through the Proxy. We ar ...

The touch events are not detected on Pixi.js when buttons are placed on a stage that has been both scaled and

Currently, I am developing a game using pixi js. In order to ensure that the game appears consistent on all screens, I have implemented the following scaling logic: this.scale = Math.max(this.viewWidth, this.viewHeight) / (2048 * this.ratio); Additionall ...

Issue encountered: Incompatibility between Mongoose Populate and Array.push()

After reading a different post addressing the same issue, I still couldn't figure out how to implement the solution into my own scenario. The discussion revolved around the topic of node js Array.push() not working using mongoose. In my Mongoose asyn ...

Is there someone who can assist me in transforming this constructor function into a factory function using Javascript?

const createAppError = (message, status) => { return { message, status }; }; This is the equivalent code using factory functions to create an AppError with a message and status. It achieves the same result as the constructor fun ...

Solution to ensure fixed header with correct z-index placement

Everything is functioning correctly, except for the issue that arises when scrolling down to view thumbnails. The left bar covers the thumbnail section, making it impossible to select items. I suspect that the z-index of a div is causing this problem. I ha ...

What could be causing the input field state to remain static even as I type in the MUI textField?

In my React.js component, I am facing an issue where the textField is not updating when I try to type anything. Upon debugging, I discovered that when the first character is entered, the component re-renders and loses its previous state, causing the textF ...

What should I verify if the Grails application is not loading on IE9 exclusively?

In the process of developing a Grails project that incorporates some JS code, I encountered an issue where the project ran smoothly on Google Chrome (v34.0.1847.116 m) and Mozilla Firefox (v28.0), but failed to start on IE (v9.0.23), resulting in a blank s ...

Utilizing Vue.js i18n for a multi-line text display

Currently, I am implementing i18n single file component in order to provide translation support for my application. In order to achieve this, I have been utilizing the i18n tag as shown below: <i18n> { "fr": { "text": "Lore ...

Function that returns a lookup map for TypeScript enums

For my React project, I've created a function that transforms a lookup class into an array that can be used. The function is functioning properly, but it seems to loop through the enum twice, resulting in undefined values for the first iteration. Alt ...

utilizing various ajax functions

I'm having trouble using additional functions with the "complete:" option in JQuery ajax after the "selectOptionSort" function. Can anyone help me figure out what's wrong? $('#tipos').change(function(){ $("#marcas ...

Two sidebar panels displayed in the same tab on the Navbar page

In the Shiny navbarpage, is it possible to add 2 sidebar panels with space in between, as illustrated in the diagram linked below? Can we use HTML tags to achieve this spacing? https://i.sstatic.net/jXBXo.png Below is the code for it (Essentially, I requ ...

Conceal the Ipad keyboard while still retaining the ability to input text using a customized keyboard

I need to create an input field where users can enter numbers using a custom "keyboard" created with CSS/HTML on the page. This means I don't want the iPad's keyboard to pop up. Most of the solutions I've come across involve removing focus f ...

Are the buttons appearing within a pop-up display?

I am having an issue with my Javascript popup buttons. Whenever the popup appears, the buttons that come after the one clicked appear on top of the popup container, and the previous buttons appear behind it. How can I ensure that the popup container displa ...

Promises and Their Valuable Variables

Recently I began learning JavaScript and I'm encountering some confusion. Here's the code snippet that is causing me trouble: api.posts .browse({ limit: 5, include: 'tags,authors' }) .then(posts => { posts.forEach(post =&g ...

Mastering the art of iterating through an array of objects in Vue/Nuxt

<template> <div> <h1>Greetings from the World</h1> <div> <span :for="day in days">{{ day }} </span> </div> </div> </template> <script> expo ...

Is there a way to automatically change specific characters as a user types in an input field?

I'm facing an issue with replacing some characters dynamically. The goal is to ensure that user-input text is URL-friendly for constructing a URL: function slugify(string) { const a = "àáâäæãåāăąçćčđďèéêëēėęěğǵḧîïí ...

Full height sidebars with adjustable scrolling bars

Currently, I am working on an Angular application that features a fixed bootstrap navbar at the top and a sidebar container with a header and a scrollable list of content. To achieve this layout, I am using specific CSS classes: .main-wrapper { heigh ...

Retrieve geographical coordinates from image metadata using JavaScript

Seeking help with extracting the GPS Exif tag from images using NodeJS. The data is currently structured as follows: { "gps": { "GPSTimeStamp": [2147483647, 76, 41], "GPSLongitude": [76, 41, 56.622], "GPSLatitude": [30, 43, 8 ...

Is it possible for me to alter the script for my button's onclick

Is there a way to replicate all properties of a div when creating a clone using JavaScript code? I have an existing script that successfully creates a clone of a div when a button is pressed, but it does not copy the CSS properties. How can I ensure that t ...