lunr
lunr

Reputation: 5269

jquery ".prop()" does not work before appending to body

I used jquery to create an initially blank select element. I tried this:

$('<select><option>1<option>2</select>').prop('selectedIndex', -1).appendTo(document.body);

This successfully creates a select box, but it is not blank. Through experimenting, i found out that this works:

var $new = $('<select><option>1<option>2</select>').appendTo(document.body);
$new.prop('selectedIndex', -1);

What is different between those two is that when theselectedIndex property is set: before or after it is appended to the body. Can you explain reason beneath this?

Here is a JSFiddle: http://jsfiddle.net/R9auG/

Upvotes: 2

Views: 277

Answers (2)

user166560
user166560

Reputation:

If there are no options with the selected attribute when the browser first renders the element, it'll choose the first one.

I thought this was required by the spec, but it turns out that this was undefined in HTML 4.01 and I can't find anything about it at all in the current spec.

There is this, from the HTML 4.01 spec:

Note. Since existing implementations handle this case differently, the current specification differs from RFC 1866 ([RFC1866] section 8.1.3), which states:

The initial state has the first option selected, unless a SELECTED attribute is present on any of the elements.

Since user agent behavior differs, authors should ensure that each menu includes a default pre-selected OPTION.

In any case, that does seem to be how it's still handled.

In your first example, the browser doesn't understand the selectedIndex property yet because the DOM object doesn't exist until after the select element is rendered. That property is created when the browser creates the object. You can't change the property of an object that doesn't exist yet.

This is confusing... we're dealing with two separate types of objects: a jQuery object and a DOM object.

In your second example, the browser renders the select element and creates an object with a selectedIndex property which you immediately change to say that nothing (-1) is selected.

You might find the "placeholder label option" useful if you read about it in the details of the select element specification.

Upvotes: 2

Jake
Jake

Reputation: 4234

It just looks to me like the $.prop() function must run after the item is appended to the body. Here's an example using your first code: http://jsfiddle.net/jakelauer/R9auG/311/

And the code itself:

$('<select><option>1</option><option>2</option></select>')
    .appendTo(document.body)
    .prop('selectedIndex', -1);

PS - You are not closing your <option> tags in the jQuery. The browser is smart and is fixing this for you, but it could cause big problems if you don't close them like I did in my example.

Upvotes: 2

Related Questions