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

Using a combination of AND and OR in XPATH

Recently, I encountered the following HTML code: <div><h6>abc/h6><p>date</p></div> Using Selenium, I managed to locate this element based on text. However, the issue arises when <h6> can contain various words like "d ...

When attempting to integrate Angular 1.4's new router with components, an issue arises where a warning is triggered stating, "Failed to instantiate controller HeadlinesController

Attempting to work with Angular for the first time and struggling to load a component using data from an http request. Currently encountering a warning when attempting to execute the code with the HTTP request. Receiving a "Could not instantiate control ...

SDTT: "Please ensure that the image field has a value before continuing"

I recently added this code snippet to a LocalBusiness listing (using guidance from this resource): <div itemscope itemtype="http://schema.org/LocalBusiness"> <div itemprop="image" itemscope="" itemtype="http://schema.org/ImageObject"> ...

Is there a regular expression that can be used to extract sentences from HTML

As I delve into the world of HTML parsing, I'm starting to understand that using regular expressions for this task is not always the best approach. However, in my Perl class, I am currently experimenting with utilizing regular expressions to extract a ...

Javascript's event.keyCode does not capture the Backspace or Delete keys in Internet Explorer

Looking to detect when the Backspace and Delete keys are pressed using javascript/jQuery, I have the following code: $("textarea[name=txt]").keypress(function(e){ var keycode = e.keyCode ? e.keyCode : e.which; if(keycode == 8){ // backspace ...

Ways to prevent a background image from centering at a designated width

Is it possible to prevent a background image from centering at a specific width? To demonstrate the issue, try narrowing the width of the website linked below until scroll bars appear. Take note of how the background image stays centered while other eleme ...

How can Javascript or Jquery determine the specific event assigned to an object?

Is it possible to retrieve the properties of HTML elements using their name or id? For example: document.getElementById('id').value; //Accessing element property in JavaScript $('#id').attr('class'); // Accessing correspond ...

Whenever I execute the code, my if statement seems to interpret the conditions as true regardless of the actual values

let num = (Math.floor(Math.random() * 6 + 1)) console.log(num) if (num === 6) console.log('Wow, you hit the jackpot with a rarity of 1/6!') The above code snippet generates a random number between 1 and 6, then prints "that was a 1/6 chance" if ...

How can you incorporate TypeScript's dictionary type within a Mongoose schema?

When using TypeScript, the dictionary type format is: { [key: string]: string; } However, when I try to define a custom schema in mongoose, it doesn't work as expected. const users = new Schema({ [key: string]: String, }); I also attempted t ...

Avoid displaying duplicate items from the array

Utilizing react js, I am attempting to iterate through an array of objects and display the name of each object in the array: const arr = [ { name:"Bill", age:88 }, { name:"Bill", age:18 }, { name:"Jack", age:55 }, ] ...

Creating a dynamic cascading dropdown list with Vue.js: Step-by-step guide

I successfully implemented a dropdown list using Vue.js, but now I want to add another similar list. How can I set this up? Here are the codes for both dropdown lists: var addUserVue = new Vue({ el: "#app", data: { heading: "Vue Select Cas ...

Embed watermark on the Username and Password fields of asp:Login control

Seeking help to watermark the Username and Password fields of asp:Login controls using jQuery, I have attempted different methods to reference the control ID: $('#<%=ClientID.Login1_UserName %>').watermark('watermark', 'User ...

Personalize the jquery autocomplete outcome

I'm currently utilizing jQuery autocomplete along with a remote data source. $( "input#searchbar" ).autocomplete({ source: function( request, response ) { $.ajax({type: "post", mode: "abort", dataType: ...

Utilizing document.write() for displaying markup content

I have an inline SVG stored as a variable on my webpage and I am making some changes to it. How can I display viewText on the page (not the SVG image) with the modifications? What is the best way to make viewText appear on the page? For instance: ...

Searching for particular JQuery nested values located within an input element

<input id="ctl00_PlaceHolderMain_RadButtonMango_ClientState" name="ctl00_PlaceHolderMain_RadButtonMango_ClientState" type="hidden" value="{"text":"Mango","value":"Mango","checked":true,"target":"","navigateUrl":"","commandName":"","commandArgument":""," ...

The final piece left in stitching together an array

Issue I have been struggling with this code for some time now and I can't seem to figure out the solution. I am receiving 3 values from inputs and trying to remove all the empty spaces "" in the array, but when I execute the code, it displays the foll ...

Is there a way to retrieve the Angular-Redux store in a child module?

Within my Angular application, I utilize angular-redux for managing the application state. In my main module, I have defined the redux store in the following manner: export class MainModule { constructor(private ngRedux: NgRedux<MainAppState>, ...

Names like jQuery and ASP.NET are well-known in the world

What is the proper method to select a control rendered by ASP.NET using jQuery? For instance, if there is a checkbox generated as: <input id="ctl00_Content_chkOk" type="checkbox" name="ctl00$Content$chkOk" /> Attempting to check if it's check ...

What is the best way to link the width and height of a div with form fields?

I need to implement a feature where I can create multiple div elements that are draggable and resizable, and have their properties like width, height, etc. linked to corresponding objects in an array. For example, if I create six divs, there should be six ...

Encountering a NaN outcome when summing values from various select options

I'm working on a project that involves adding up the prices based on the surface chosen by the user. I'm struggling with calculating the partial cost when the user's choice changes. totalSum.ts num: Calculation totalAmount: number cate ...