开发者

chrome and css issue

I have this ht开发者_开发百科ml code

<div id = 'status'>
<span class="formw" style="background-color:#FBD9E5;">
some text
</span>
</div>

When the following javascript gets executed

$('status').style.backgroundColor = '#99e83f'; 

chrome throws the following error:

Uncaught TypeError: Cannot read property 'style' of null

Anybody knows the reason?

Update: I am using Prototype.


There are two errors in:

$('status').style.backgroundColor = '#99e83f'; 

First:

  • You are missing the # to specify the id in your selector for status div.

Second:

  • The style property won't work on jQuery object that is $('#status').

Solution:

Method One:

$('#status')[0].style.backgroundColor = '#99e83f'; 

The [0] added above converts jQuery object into normal DOM element so that style property is applied successfully.

Method Two:

('#status').css('background-color','#99e83f');


You specifically mention Google Chrome. Chrome is stricter about standards than most, especially if your document has a DOCTYPE.

The markup <div id = 'status'> makes me suspicious. Although most browsers are forgiving about common syntax errors it is possible that by having id space separated from equals causes it to be treated as a boolean attribute, which is equivalent to <div id="id">.

You can test this opening the javascript console (Shift+Ctrl+J) and see what results from typing:

$('status')
$('id')

For a solution try it like this:

<div id="status">

PS. I would guess you don't actually want to alter the DIV's style but the span's, for which any of the following is correct.

$$('#status .formw').style.backgroundColor = '#99e83f';

$$('#status span').style.backgroundColor = '#99e83f';

$('status').down('.formw').style.backgroundColor = '#99e83f';

$('status').select('span').style.backgroundColor = '#99e83f';


Try

$('#status').style.backgroundColor = '#99e83f';


if you are using jquery try this

$('#status').css('background-color','green');

this should work


Sometimes there are some DOM hiccups when it comes to elements in prototype when you are using the classic DOM methods.

Instead use the defined methods in prototype to read and set styles for an element.

The two methods you are interested in are:

  • .setStyle, documentation( http://www.prototypejs.org/api/element/setStyle )
  • .getStyle, documentation( http://www.prototypejs.org/api/element/getStyle )

So, in example, if you want to set the background of your element, you would use:

$('status').setStyle( { 'background-color' : '#99e83f' } );

If you wanted to read the attribute, you would use:

$('status').getStyle( 'background-color' )

For the jquery crowd, the $( 'element_id' ) is the equivalent shorthand for document.getElementById( 'element_id' ). If you wanted to get the element by selector, it would be $$( '#element_id' ).first().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜