1

I have the following code in my application. The first two lines paint an item in the table just fine. But when I just want to get the color of this item (which is "#FFFFFF") it returns undefined. Those lines go in exactly that order, and there is nothing in between them.

var $item = $('#10.row').find('#3.col');
$item.attr('bgcolor', '#FFFFFF');
console.log($item.css('bgcolor'));

2 Answers 2

2

Note that $item.attr('bgcolor', '#FFFFFF') will make the HTML look like this:

<div id="10" class="row">
  <!-- bgcolor attribute added by JQuery: -->
  <div id="3" class="col" bgcolor="#FFFFFF"></div>
</div>

To set and get the CSS background color, use one of the following (both are valid in JQuery):

// Only use second parameter to set in both cases.
$item.css( "background-color", "#FFFFFF" ) 
// OR
$item.css( "backgroundColor", "#FFFFFF" )

Outputs like this:

<div id="3" class="col" style="background-color:#FFFFFF;"></div>

If you really want to add the HTML attribute bgcolor, you can fetch that attribute like this:

console.log($item.attr('bgcolor'));

So the final JS would look like this:

var $item = $('#10.row').find('#3.col');
$item.css('background-color', '#FFFFFF');
console.log($item.css('background-color'));

Or like this:

var $item = $('#10.row').find('#3.col');
$item.attr('bgcolor', '#FFFFFF');
console.log($item.attr('bgcolor'));
Sign up to request clarification or add additional context in comments.

Comments

0

You're setting the (deprecated) bgcolor attribute and then trying to access the CSS (non-existent) bgcolor CSS property which both doesn't exist, and isn't set.

As noted elsewhere, to set the background-color *set the background-color:

var $item = $('#10.row').find('#3.col');
$item.css('background-gcolor', '#FFFFFF');
console.log($item.css('background-color'));

The two are not interchangeable or equivalent, and bgcolor should no longer be used.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.