Lafani
Lafani

Reputation: 19

Creating elements using jQuery

I've written a JS program which works fine if I use the following line of code:

    li = $("<li data-role='collapsible' data-iconpos='right' data-inset='false'></li>");

But if I change the above line to as follows, it stops working:

    li = $('<li/>, {
          data-role: 'collapsible'
          data-iconpos: 'right'
          data-shadow: 'false'
          data-corners: 'false'
    });

What is wrong here?

EDIT - Additional code that is failing:

    a = $('<a/>', {
        href: fSelectedContent[i].hPageURL,
        click: function () { mSelectCount(fSelectedContent[i].rContentID);},
        html: fSelectedContent[i].rContentName
    });

Upvotes: 0

Views: 80

Answers (3)

ne1410s
ne1410s

Reputation: 7102

An alternative would have been to use:

$('<li/>').attr({
    "data-role": 'collapsible',
    "data-iconpos": 'right',
    "data-shadow": false,
    "data-corners": false
});

But each to their own I guess :)

Upvotes: 2

Quentin
Quentin

Reputation: 944438

In a JavaScript object literal, a property name must be an identifier or a string.

An identifier cannot include a - character, so you have to use strings.

Quote your property names.


You also need a comma between each key:value pair.


You also need to put a quote to end the string for the <li/>.


li = $('<li/>', {
      "data-role": 'collapsible',
      "data-iconpos": 'right',
      "data-shadow": 'false',
      "data-corners": 'false'
});

Upvotes: 6

Brad
Brad

Reputation: 163593

For string literals, if you want to have them roll to the next line you need to use a backslash at the end of the line.

var something = 'line 1 \
    line2';

In your case though, you're just missing an end-quote after <li/>.

$('<li/>', {

(And, do note Quentin's suggestion above of having proper object literal keys. You need to quote them if you have - in there, or other reserved characters. +1 Quentin.)

Upvotes: 0

Related Questions