Reputation: 25
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.
Upvotes: 0
Views: 583
Reputation: 29739
You can do that with the use of .css():
$('span.swatch > strong').css('background-color', $('span.swatch').css('background-color'));
Or a more generic approach:
var strong = $('span.swatch > strong');
strong.css('background-color', strong.parent().css('background-color'));
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'));
See also vzwick`s answer for converting the rgb string to the commonly used hex format.
Upvotes: 3
Reputation: 11044
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.
Upvotes: 1