How to add a property to an element?

389 views Asked by At

Keeping in mind the addition of .prop() in jQuery replacing .attr() for many boolean type attributes/ properties of an element. My question is how to add a 'Property' in the following code?

The following set of code is functionally doing what I require it to do, but in my browser debug section I see a warning "JQMIGRATE: jQuery.fn.attr('selected') may use property instead of attribute" referring jquery-migrate-1.2.1.js

                    $("<select />",{
                        "class": "align-select",
                        id: "align_select_123"
                    }).append(
                            $("<option />",{
                                value: "left",
                                selected: "selected",
                                html: "Left"
                            }),
                            $("<option />",{
                                value: "right",
                                html: "Right"
                            }),
                            $("<option />",{
                                value: "centre",
                                html: "Centre"
                            }),
                            $("<option />",{
                                value: "justify",
                                html: "Justified"
                            })
                        )

The above mentioned warning refers to the 7th line of the code i.e. selected: "selected". What is the possible good way to get same code working with out generating this warning?
I have tired:

$("<option />",{
    value: "left",
    html: "Left",
    selected
})

but it didn't worked!!

2

There are 2 answers

0
Karl-André Gagnon On BEST ANSWER

Although I would still use the attribute in this context for readability (since it's true that prop should be used), to set the property would be in an other call :

$("<option />",{
    value: "left",
    html: "Left", 
}).prop('selected', true),
1
Mathieu Labrie Parent On

Have you tried like this ?

$("<option />", {
    value   : "left",
    selected: "selected",
    html    : "Left"
}