javascriptjqueryjquery-migrate

How to add a property to an element?


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!!


Solution

  • 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),