views:

166

answers:

2

I swear the following code used to work, even in IE7 but now i get

Error: Object doesn't support this property or method

$('div').each(function() {
  if(! this.attr('id').startsWith('light') ) {  
    this.css('zIndex', zIndexNumber);
    zIndexNumber -= 10;
  }
});

Any ideas?

SOLUTION

        $('div').each(function() {

        var divId = new String ( $(this).attr('id') );

        if(! divId.indexOf('light') == 0 ) {  
            $(this).css('zIndex', zIndexNumber);
            zIndexNumber -= 10;
        }

        });
+3  A: 

It should be

$(this)

instead of

this

$(this) creates the jQuery object on which you can use all the jQuery functions. this is "only" the DOM element and this element has no e.g. properties attr() or css().

Update:

Are you sure .startsWith() exists? Have you defined it yourself because JS has no such function afaik.

Try:

if($(this).attr('id').indexOf('light') == 0)
Felix Kling
Yes, that was the first version of the script, but it was generating the same error.
L. De Leo
lbolognini: what happens when you enter the following in the address bar? `javascript:alert(''.startsWith);`
janmoesen
On IE7 that gives me undefined
L. De Leo
@lbolognini: Have you tried it the way I proposed? `startsWith` is not a JS function.
Felix Kling
yes, i've posted my definitive version. thanks for your help
L. De Leo
+1  A: 

I know you've already accepted an answer, but based on your code it looks like you don't need to use an if statement at all if you change your selector:

$('div[id^=light]').each(function() {

        $(this).css('zIndex', zIndexNumber);
        zIndexNumber -= 10;

});

div[id^=light] in your selector means "get all divs whose id begins with 'light'".

Similarly, div[id$=light] will select all divs whose id ends with 'light', and div[id*=light] will select all divs whose id contains 'light' anywhere in it.

This isn't even limited to id. You can use this on any attributes on any element. I know I found this very useful when I first discovered it.

Aaron
Yeah good approach, upmodded
L. De Leo