Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain this jQuery selector?

I'm trying to debug another developers code, and I can't for the life of me figure out what is being stored in this variable:

var dl = $("<dl>",{class: 'my_class'});

This line is generating an "Expected identifier, string or number" error message in IE8 and lower, but none of the other browsers, and I'm trying to figure out if there's some other way I can accomplish the same thing, with different syntax.

Any advice would be appreciated.

like image 825
user1380281 Avatar asked Oct 03 '12 19:10

user1380281


1 Answers

It's creating a dl element (wrapped in a jQuery object) with a class attribute with the value of my_class. See the jQuery docs for more about this form of the function.

You get the error because class is a reserved word in JavaScript. You can fix it by quoting it:

var dl = $("<dl>", { "class": "my_class" });

Alternatively, you could set the className property instead (which you won't have to quote in any browser):

var dl = $("<dl>", { className: "my_class" });

Note that the ES5 spec says you can use reserved words as property names. But since you apparently need to support old versions of IE, you will have to forget about that and quote them anyway. If you just drop support for IE below version 9, you won't have to change your code at all ;)

like image 106
James Allardice Avatar answered Sep 22 '22 14:09

James Allardice