What is the procedure for assigning an element's background-color to match its class name?

Is there a way to use jQuery to make the background color of a span element match its class?

$(function() {
$("span").css("background-color")
});
span {
  display: inline-block;
  width: 5px;
  height: 5px;
  border: solid #0a0a0a 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="red"></span>
<span class="red"></span>
<span class="red"></span>
<span class="blue"></span>
<span class="silver"></span>
<span class="black"></span>
<span class="black"></span>
<span class="silver"></span>
<span class="grey"></span>
<span class="silver"></span>
<span class="green"></span>
<span class="lightgreen"></span>
<span class="gold"></span>
<span class="yellow"></span>
<span class="yellow"></span>
<span class="yellow"></span>
<span class="yellow"></span>
<span class="yellow"></span>
<span class="yellow"></span>
<span class="gold"></span>
<span class="gold"></span>
<span class="gold"></span>
<span class="red"></span>
<span class="red"></span>
<span class="red"></span>
<span class="red"></span>
<span class="green"></span>
<span class="green"></span>
<span class="green"></span>
<span class="green"></span>
<span class="lightgreen"></span>
<span class="lightgreen"></span>
<span class="green"></span>
<span class="green"></span>
<span class="gold"></span>
<span class="gold"></span>
<span class="orange"></span>

Answer №1

You have the option to provide a function as the second parameter, which can determine the class name dynamically

$(function() {
  $("span").css("background-color", function() {
    return this.className;
  })
});
span {
  display: inline-block;
  width: 5px;
  height: 5px;
  border: solid #0a0a0a 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="red"></span><span class="red"></span><span class="red"></span><span class="blue"></span><span class="silver"></span><span class="black"></span><span class="black"></span><span class="silver"></span><span class="grey"></span><span class="silver"></span>
<span
class="green"></span><span class="lightgreen"></span><span class="gold"></span><span class="yellow"></span><span class="yellow"></span><span class="yellow"></span><span class="yellow"></span><span class="yellow"></span><span class="yellow"></span><span class="gold"></span>
  <span
  class="gold"></span><span class="gold"></span><span class="red"></span><span class="red"></span><span class="red"></span><span class="red"></span><span class="green"></span><span class="green"></span><span class="green"></span><span class="green"></span><span class="lightgreen"></span>
    <span
    class="lightgreen"></span><span class="green"></span><span class="green"></span><span class="gold"></span><span class="gold"></span><span class="orange"></span>

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

Popper.js failing to initialize during page load

After attempting to initialize Popper.js as shown below, I am encountering an issue where nothing is happening. $().ready(function(){ $('[data-toggle="tooltip"]').tooltip(); }); Interestingly, when I apply the same code to a button, it w ...

Vue.js - Capturing a scroll event within a vuetify v-dialog component

Currently, I am working on a JavaScript project that involves implementing a 'scroll-to-top' button within a Vuetify v-dialog component. The button should only appear after the user has scrolled down by 20px along the y-axis. Within the v-dialog, ...

The issue with flexslider not functioning properly arises when used in conjunction with ajax Magnific popup

Having trouble integrating flexslider into magnific popup as the script inside the popup is not functioning properly. The magnific popup is being loaded using the wordpress function wp_enqueue_script(): jQuery(document).ready(function($){ $(&apo ...

Using pg-promise to insert a UUID into the database

I am in the process of setting up a new server and I want each customer to have a unique UUID identifier. My goal is to allow the customers name, parent company, and internal id to be input through a web interface, while the UUID is generated on the server ...

Creating complex concave shapes using Three.js from a point cloud

Currently facing a challenge in dynamically creating shapes in three.js from a point cloud. While ConvexGeometry works well for convex shapes, it becomes complex when dealing with concave shapes. The process involves drawing a line on the 2D plane (red li ...

What is the best way to switch to a new HTML page without causing a page refresh or altering the URL?

Is there a way to dynamically load an HTML page without refreshing the page or altering its URL? For instance, if I am currently on the http://localhost/sample/home page and I want to switch to the contact us section by clicking on a link, is it possible t ...

Is it possible to fill an array with the children of an element using

Just a quick question for the sake of simplicity... At the moment, my code looks like this: var categoryList = []; $('#share').children().each(function() { categoryList.push($(this).html()); }); I was wondering if there is a more efficient ...

Is there a way I can set a variable as global in a jade template?

I am trying to pass a global object to a jade template so that I can use it for various purposes later on. For instance: app.get("/", function(req, res){ var options = { myGlobal : {// This is the object I want to be global "prop ...

The CSS cubic-bezier fails to smoothly transition back to its initial position

I created an animation that works perfectly when hovering over the target elements, however, it doesn't smoothly transition back to its original position when the cursor moves outside of the target element. Instead, it snaps back abruptly and unattrac ...

In strict mode, duplicate data properties are not allowed in object literals when using grunt-connect-proxy

I recently started following a tutorial on AngularJS titled "Hands on Angularjs" by Tutsplus. In the tutorial, the instructor uses the grunt-connect-proxy package to redirect ajax requests to a Rails server running on localhost:3000. However, I believe the ...

Unlock TypeScript code suggestions for extended objects

In my app, I use a configuration file named conf.ts to consolidate config values from other files for better organization. By merging these values, it becomes more convenient to access them using Conf.MY_LONG_NAMED_VALUE rather than Conf.SubCategory.MY_LON ...

Customizing DataTables row data with JSON inputs

Upon receiving JSON data on my website, it includes an array, an array of objects, and a string. For example: data = { labels: ['a', 'b', 'c', 'd', 'e',] , staff: [ {'name' : 'aaa', &a ...

What is the best way to use jQuery to adjust the size of a slider image based on a percentage of the browser window

I've been searching all over for a solution to this issue, but so far I haven't had any luck. Basically, I have an image that is 1800 pixels wide by 500 pixels high. I need this image to adapt to all screen resolutions. Instead of having a fixed ...

Does jqgrid navgrid have an event called "on Refresh"?

Is there a way to trigger an event before the grid automatically refreshes? I am looking for something similar to "onSearch" but for the reset button. Below is the code snippet for the navgrid: $("#jqGrid").jqGrid('navGrid','#jqGridPag ...

What is the best way to format 100K to appear as 100,000?

function formatNumberWithCommas(num) { return num >= 1000 ? `${Number.parseFloat((num).toFixed(3))}` : num; } ...

Steps for incorporating "about minutes ago, about hours ago, etc;" into a .filter for an Angular/Ionic v1 project

Can someone help me figure out how to incorporate phrases like "from now," "ago," etc. into a JS filter in my ionic v1 project for WordPress without using UTC Date? I am currently working on an Ionic v1 app that is native to WordPress, so it's crucia ...

Revamp the jQuery dynamic form script to be adaptable for various uses

My form is designed with simplicity in mind, allowing users to choose a color and then an item from that color category. The second selection updates based on the first input. Currently, I have a jQuery script that targets the first element by ID and chan ...

Setting new query parameters while maintaining existing ones without deleting them in Next.js v13

"use client"; import { useCallback, useEffect, useState } from "react"; import Accordion from "../accordion/accordion"; import { useRouter, usePathname, useSearchParams, useParams, } from "next/navigation"; i ...

How to style text alignment and create a toggle button using HTML and CSS

My attempt at creating a custom toggle button using an HTML input checkbox and custom CSS has resulted in a misalignment between the text and the toggle button itself. Despite my efforts to adjust margins, padding, and heights, I have been unable to resolv ...

Explain the concept of paragraph spacing in Word, including how it is

When working with my ms word 2010 document, I often use the includetext-function to incorporate HTML content: { INCLUDETEXT "test.html" } Here is an example of the HTML code that I am trying to include: <html> <head> <meta http-equiv="Co ...