Passing the hex code value of the background-color to the .text() function

My goal is to dynamically read the hexadecimal code from the <span> tag and set it as the background color of the same tag using jQuery. Currently, I have code that achieves this with specific variables, but I want to make it more dynamic.

$(document).ready(function() {
  var primeCol = $('.colorBlocks div:eq(0) span').text();
  $(".colorBlocks div:eq(0) span").css("background-color", primeCol);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <span>#0099cc</span>
</div>
<div>
  <span>Primary Color 2 is #OOffcc</span>
</div>

I'm looking to modify the code so that it utilizes $(this).text() and can extract the hex code from any <span> tag, even if it's embedded within text like in the second <span> tag. If anyone can provide assistance with this, I would greatly appreciate it as I'm currently facing challenges with it.

Answer №1

If you want to achieve this, you can use a function with the css() method to evaluate each element in the matched set. Instead of targeting the first element of all div elements, you can target the first element within each child div by using :first-child. Here's an example:

$(document).ready(function() {
  $('.colorBlocks div:first-child span').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="colorBlocks">
  <div>
    <span>#0099cc</span>
  </div>
  <div>
    <span>Primary Color 2 is #OOffcc</span>
  </div>
</div>
<div class="colorBlocks">
  <div>
    <span>#cc0000</span>
  </div>
  <div>
    <span>Primary Color 2 is #OOffcc</span>
  </div>
</div>

Alternatively, if you want to apply this to all spans and find any hexadecimal value within them, you can remove the :first-child selector and use a regular expression to locate the hex value:

$(document).ready(function() {
  $('.colorBlocks div span').css('background-color', function() {
    return /#[0-9A-F]{6}/gi.exec($(this).text());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="colorBlocks">
  <div>
    <span>#0099cc</span>
  </div>
  <div>
    <span>Primary Color 2 is #00ffcc</span>
  </div>
</div>
<div class="colorBlocks">
  <div>
    <span>#cc0000</span>
  </div>
  <div>
    <span>Primary Color 2 is #00ffcc</span>
  </div>
</div>
<div class="colorBlocks">
  <div>
    <span>#00cc00</span>
  </div>
  <div>
    <span>Primary Color 3 is not specified</span>
  </div>
</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

How can I make CSS text-overflow ellipsis trigger a pop-up to display lengthy text when clicked?

I'm encountering an issue with a lengthy sentence in a table cell which I've truncated using text-overflow to display ellipsis. Is there a way to enable users to click on the dots (...) and view the full text in a popup window? table { wi ...

Using clip-path in SVG works perfectly on images, but unfortunately it does not work on div

I came across an interesting example on MDN about using a clip-path SVG on an image. However, it seems that the same clip-path does not work properly when applied to a div. Can anyone shed some light on: The reason why this code is not achieving the inte ...

Navigate through an image by panning or scrolling within a div container

I have a container div with an image inside. <div id="container"> <img id="image" src ....> </div> I also have a function that retrieves the image by its ID and applies zoom using styles like this: image.style.transform = `scale(${v ...

How to Align Items Horizontally in React Material UI Grid for Containers of Varying Item Counts

I've been utilizing the React Material UI Grid System to arrange my elements on the page, which utilizes flexboxes internally. While everything is functioning properly, I'm struggling with horizontally aligning items in containers that have vary ...

Can you please tell me the term used to describe when a background adjusts and follows the movement of a mouse cursor?

Just wrapped up freeCodeCamp's HTML & CSS Responsive Web Design course and noticed a cool feature in some portfolios that I'd like to learn. However, I'm not sure what it's called. Here are some examples: The video game Escape From Ta ...

Retrieve data from database using ASP.NET and display it without any formatting or HTML tags

Being new to jquery and asp.net, I hope you can bear with me if my question seems too basic. Currently, I am working with a jquery autocomplete plugin that requires the data it retrieves asynchronously to be in a specific format of plain text: product1|pr ...

Unable to retrieve file name with Jquery Ajax and PHP due to error

Trying to display the file name "echo $_FILES['userfile']['name'];" on browser console resulted in "function File() { [native code] }". Below is the jQuery code snippet: <?= form_open_multipart('',' id="importform" m ...

What impact does including a parent View Tag have on the styling in React Native?

Why does adding a View parent break my styles? Could React Native's View tag have default styles that I'm not aware of? Displayed below is the Button component along with screenshots demonstrating the difference when using and not using the View ...

Issues with negative margin causing background image to not display correctly

Hey there, I'm currently trying to add a background image to the bottom left of my webpage. The layout includes both left and right sidebars. Unfortunately, I've encountered some issues with positioning the image using CSS in both the left sideba ...

Adjust the size of the text and save it in a cookie for later use

I am in need of a script that can dynamically increase and decrease the font size on a website while retaining the user's chosen setting even after they return to the site. I believe utilizing cookies is the way to achieve this functionality. Despite ...

I am experiencing difficulty in retrieving the result for the following code snippet

I'm currently attempting to retrieve data for my chart from a data.csv file. <!DOCTYPE html> <html> <head> <title>D3 test</title> <style> .grid .tick { ...

Modifying JQuery function to target two IDs instead of just one

I am utilizing a bootstrap 5 tablist on my website that allows for navigating between tabs using custom left and right arrows. If I wish to introduce a second bootstrap 5 tablist with a new unique ID, how can I modify the code to integrate the new ID and e ...

Using ajax to execute a basic PHP function

How can I execute a PHP function with a query using AJAX? This is my HTML: <input type="submit" value="Open Process" name="openProcess" id="openProcess" onclick="javascript:applicationOpenProcess()" > And here's my PHP function: function ope ...

What is the best way to position two divs side by side while maintaining their individual padding?

When I remove the padding as shown, the website functions correctly with two div columns next to each other. However, upon adding padding, the #right div shifts downwards. How can I ensure it works as intended with padding included? HTML: Two divs direct ...

"Utilizing Bootstrap's Table Features within the Moodle Platform

Hey there! I'm currently in the process of updating a client's Moodle website. Our goal is to create responsive tables on the homepage, but I've encountered some challenges. Due to conflicts with other Moodle libraries, I wasn't able to ...

Responsive Navigation Bar with Bootstrap

Struggling with the Bootstrap 4 navbar issue, specifically trying to close it when the <a> within the <li> tag is clicked. Experimented with data-toggle="collapse" data-target=".navbar-collapse.show" inside the <a> tag and it worked, but ...

What is the best method for extracting click data from dynamically generated elements?

This snippet of code creates a loop that dynamically adds li elements to the #carList. for (var i = 0; i < car.length; i++) { var carNow = car[i]; $('#carList').append("<li>" + carNow.carName + < ...

Connect the mileage tracker to a Datalist or grid view component

I recently downloaded the Odometer Sample from , however, I am facing an issue where only the first element in the Datalist is getting the Odometer display, while others are not displaying it. Here is the snippet of code: <script type="text/javascript" ...

small screen right-side navigation with Bootstrap 4

My goal is to have the logo image on the left and the navigation on the right for xs devices, and the logo in the center with navigation on the left for sm devices. However, I am facing an issue where the navigation does not align to the right on xs device ...

Calculate the combined total of two inputted values instantly

Is there a way to add two separate numerical inputs together in real-time and display the sum in a third variable? Here's a clearer explanation: First Variable: 100 (input) Second Variable: 150 (input) Sum: 250 (calculated, not input) Any suggesti ...