0

I want to copy the background-color value and paste it in within the <strong> tag:

<span class="swatch" style="background-color: #d1f2a5;"><strong>paste here</strong><em></em></span>

There will be multiple instances to copy/paste.

jake
  • 25
  • 5

2 Answers2

3

You can do that with the use of .css():

$('span.swatch > strong').css('background-color', $('span.swatch').css('background-color'));

Demo

Or a more generic approach:

var strong = $('span.swatch > strong');
strong.css('background-color', strong.parent().css('background-color'));

Demo

Update

I just realized that i might misunderstood your question, here is how you set the background color as html inner text:

var strong = $('span.swatch > strong');
strong.html(strong.parent().css('background-color'));

Demo

See also vzwick`s answer for converting the rgb string to the commonly used hex format.

Community
  • 1
  • 1
Alp
  • 29,274
  • 27
  • 120
  • 198
  • 2
    +1 However as OP has mentioned this will be done multiple times, the use of `this` and `parent` may be useful so you only have the one variable to change. – Curtis Mar 29 '12 at 11:00
1

If I got your question correctly, you're looking to programmatically insert the value of the background-color into the <strong>, right? – Working fiddle here

$('span.swatch').each(function(i,e){
    bgcolor = rgbToHex($(e).css('background-color'));
    $('> strong', e).html(bgcolor);
});

function rgbToHex(rgbString) {
    var parts = rgbString.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);

    delete (parts[0]);
    for (var i = 1; i <= 3; ++i) {
        parts[i] = parseInt(parts[i]).toString(16);
        if (parts[i].length == 1) parts[i] = '0' + parts[i];
    } 
    var hexString ='#'+parts.join('').toUpperCase(); // "#0070FF"
    return hexString;
}

P.S.: rgbToHex() is blatantly stolen from here – all credit goes to nickf.

Community
  • 1
  • 1
vzwick
  • 11,008
  • 5
  • 43
  • 63
  • This is exactly what I'm after, and your working fiddle looks great. I've copied and pasted the jQuery from it into my palette.js file, but it fails to work. I'm completely new to jQ, so I need to wrap this with something else? I have the jQuery library linked in the header, and have verified that it's working by doing a basic .hide on all elements. – jake Mar 29 '12 at 12:27
  • It's ok - I've worked it out. Thank you so much for your help :) – jake Mar 29 '12 at 12:32