2

I'm attempting to add an img tag via the following jQuery:

var parentElement = $("#sidebar");

    var img1 = $('<img />', { 
        id: 'headerImageLeft',
        src: '/Images/Header/FGM.jpg',
        class: 'img-responsive',
        style: 'float: left;',
        width: 80,
        alt: ''
    });
    img1.appendTo(parentElement);

While this seems to work correctly, I'm not certain this is the proper way to add a class. In Visual Studio 2013, I'm getting a design time warning saying I'm using a future reserved word, Is this the correct way to add a class?

3 Answers 3

4

According to the jQuery docs, because class is a reserved word, it needs to be quoted.

Property names generally do not need to be quoted unless they are reserved words (as class is in this case).

So:

var img1 = $('<img />', { 
    id: 'headerImageLeft',
    src: '/Images/Header/FGM.jpg',
    "class": 'img-responsive',
    style: 'float: left;',
    width: 80,
    alt: ''
});
Sign up to request clarification or add additional context in comments.

Comments

2

Yes, class was a reserved word in previous versions of ECMAScript standard but you could/can use the word as an IdentifierName (vs Identifiers, e.g. a variable), i.e. using "class" without quotes as a property name will work in all browsers that support version 5 of the ECMAScript. If supporting stone-aged browsers (e.g. IE8) matters you can wrap the property name with quotes otherwise you can ignore the warning.

Comments

2

Since class is an object key, it shouldn't matter that its a reserved word. You could place it within quotes to remove the Visual Studio's warning.

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.