0

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;
        }

        });

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

4 Comments

Yes, that was the first version of the script, but it was generating the same error.
lbolognini: what happens when you enter the following in the address bar? javascript:alert(''.startsWith);
On IE7 that gives me undefined
@lbolognini: Have you tried it the way I proposed? startsWith is not a JS function.
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.