One way to display a div's inner HTML as its background is to apply a CSS rule

Help needed!

<div class="container">red</div>
<div class="container">green</div>
<div class="container">#eeeeee</div>

I am trying to dynamically set background colors for multiple divs based on their inner HTML content. For example, I want the background color of the first div to be red and the second div to be green, and so on.

Since I have over 50 div elements, writing individual CSS rules for each one would be too cumbersome. As a beginner in JavaScript, is there a way to achieve this with just a few lines of code?

Answer №1

To achieve this effect, you can utilize the css() method:

$('div.container').css('background-color', function() {
    return $(this).text();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">blue</div>
<div class="container">yellow</div>
<div class="container">#cccccc</div>

For a vanilla JavaScript alternative:

var elements = document.querySelectorAll('div.container');
for (var i = 0; i < elements.length; i++) {
  elements[i].style.backgroundColor = elements[i].innerText;
}

Answer №2

Here is a solution that should meet your needs...

Using jQuery

$('.box').each(function(){
    $(this).css('background', $(this).text());
});

With vanilla JavaScript

var boxes = document.querySelectorAll('.box');
for (var j = 0; j < boxes.length; j++) 
{
  boxes[j].style.backgroundColor = boxes[j].innerText;
}

Answer №3

Let this solution brighten your day :)

$(".container").each(function (){
    $(this).css('background', $(this).text());
});

Update inspired by your feedback

A Vanilla JavaScript alternative:

If you're creating a website for up-to-date browsers, consider using querySelectorAll.

var containers = document.querySelectorAll('.container');
for(var i=0;i<containers.length;i++){
   containers[i].style.background = containers[i].innerHTML;
}

Alternatively, use this function for outdated browsers.

function getElementsByClassName(cn, rootNode) {
    if (!rootNode) {
        rootNode = document;
    } 
    for (var r=[], e=rootNode.getElementsByTagName('*'), i=e.length; i--;) {
        if ((' '+e[i].className+' ').indexOf(' '+cn+' ')>-1) {
          r.push(e[i]); 
        }
    }
    return r;  
}

var containers = getElementsByClassName('container');
for(var i=0;i<containers.length;i++){
   containers[i].style.background = containers[i].innerHTML;
}

Answer №4

To implement this functionality, you can utilize the each function in jQuery

$('.container').each(function(){
    var color = $(this).text();
    $(this).css('background',color)
})
.container{
    width:100px;
    height:100px;
    display:inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="container">red</div>
<div class="container">green</div>
<div class="container">#eeeeee</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

Exploring Next.js: Leveraging fetch to retrieve data in getServerSideProps and passing it to the client via query parameters

I'm utilizing a getServerSideProps function on the directory page. pages/catalog/index.js export async function getServerSideProps(ctx) { const response = await fetch( `http://someDomen.com/api/ipro/catalog?${ctx?.query?.page ? `page=${ctx.quer ...

Believing that members possess a certain role when they actually do not

const { Discord, MessageEmbed } = require("discord.js"); module.exports = { name: "ban", description: "bans user from guild", execute(client, message, cmd, args, Discord) { const member = message.mentions.u ...

The radio button is not appearing correctly in my HTML form

Seeking guidance as a newcomer to html and css. Looking to create a signup form using html and css, but encountering issues with the radio button not displaying in the browser. Unsure of the root cause of the problem. Any assistance would be greatly apprec ...

Resolved: Angular JS resolves circular dependencies

I encountered a Circular dependency issue while attempting to make a http.post call in a http interceptor: Circular dependency found: $http <- Ace <- authInterceptor <- $http <- $templateRequest <- $compile I understand the problem, but I ...

Unable to change placeholder in Material UI's Select Form

I'm having trouble modifying my SelectionForm. I need to update the color of the placeHolder image from red to a different color, but I can't find any properties or props on the material ui Docs to do so. Can someone assist me with this? https:/ ...

Styling in sass gets even more powerful when using custom selectors that are

Using these mixins makes it easy to work with BEM syntax in sass 3.3.2: =b($name) .#{$name} @content =e($name) &__#{$name} @content =m($name) &--#{$name} @content +b(menu) +e(item) color: grey +e(item) +m(alert) ...

implement django self,pk post-save success function

It might seem unconventional, but I'm attempting to utilize a primary key (pk) in a success function to generate a href for loading. The pk will be new and generated by the save() method. What I would like to know is how to send the self.pk pack to t ...

Access a portion of a file located on a distant server

Is it possible to read part of a remote file using Ajax without relying on server-side technologies like PHP? I believe the HTTP Range header could be utilized for this purpose, but how can we set it with Ajax? Can we even set HTTP headers in Ajax request ...

Manipulating the Datepicker onChangeMonthYear event in Jquery UI

I am currently working on customizing the appearance of specific dates within a jQuery UI datepicker. If a date is considered a holiday (meaning it matches a date in an array of specified holiday dates), I want to remove the default styling and make some m ...

What is the highest value that AutoCompleteExtender can reach?

I am currently using an AutoCompleteExtender in my code with the following configuration: <ajaxToolkit:AutoCompleteExtender runat="server" ID="autoCompleteOrigem" TargetControlID="txtClienteOrigem" ServicePath="~/Cliente/Au ...

Line divider immediately following the title on the same row

I am looking to insert a separator line immediately following the H1 tag, however my attempts have been unsuccessful. Can someone provide assistance with this? <style> #sepr { border-top-width: 3 px; border-top-style: solid; ...

Updating parent array values within child components in React

Currently, I am working on a React application where I need to save the handlers for all windows opened from the app. Previously, before using React, I stored these windows in a global array attached to the parent window, although I understand that using J ...

Real-time data updates on an Express website using Node.js

I feel like achieving something that should be simple, but all the tutorials and examples I come across seem to be overly complicated. Here's what I'm trying to do: I'm fetching weather information periodically and I want to update the text ...

Upon running `npm start`, an unexpected token error arises in the file originating from a local

After developing my first-app with the help of create-react-app, I incorporated some components from Material-UI. Everything was running smoothly when I launched it using npm start. Upon completion, I decided to extract the nice-component into its own fol ...

What is the best way to add a textfield within an image?

Does anyone have a code snippet that can generate a "search box" like the one on www.dx.com? I was shocked to find that searching for "textfield inside image" only yielded results for "image inside textfield". ...

Angular unable to find a route for external links

I am attempting to create an external link with an <a href="google.com"></a>, but for some reason it redirects me to localhost:4200/google.com... I'm not sure why this is happening, but I need to eliminate the localhost:4200. Below is the ...

How to turn off spin buttons for input type=“number” in AngularJS when using webkit

Although similar advice can be found for 'normal' Bootstrap, the solution may not be the same for AngularJS. input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button { -webkit-appearance: none; margin: ...

View a specific selected newsAPI article on its own dedicated page

I have been working on a news website and successfully displayed all the articles on a single page using the news API in nodeJs. Everything is functioning well, but now I want to show the clicked article on a separate page. Although I managed to route it t ...

Inconsistency in width of Bootstrap 4 card layouts

On my webpage, there are three cards displayed as seen in image 1. However, the cards do not have the same width in columns 1. When viewed on mobile (Chrome), the widths are all different and the bottom two cards are touching, as shown in image 2. How can ...

I am attempting to extract text from an element, but instead of the text, I received a value and am unable to click on it. This particular element is a dropdown button in a Selenium test, with

<div class="select-wrapper initialized"> <span class="caret">▼</span> <input type="text" class="select-dropdown" readonly="true" data-activates="select-options-56a6924e-42d9-1f78-1b82-fe2c1cbdfbdd" value="R3PORTS ...