Aside: for some background, interested readers may wish to visit https://bugzilla.mozilla.org/show_bug.cgi?id=720385)
In this post I want to highlight the "hole" I think that exists in the specs for datalist.
- Code: Select all
<datalist id="myDL">
<option value="zero"></option>
<option value="one"></option>
<option value="two"></option>
<option value="three"></option>
<option id="blah" value="four"></option>
</datalist>
As is now well understood (by me at least) any attempt to get the index of an option element whose parent element is a datalist is doomed to failure. It's not -1 (as anyone with any experience of the DOM might expect - clearly the mozilla guys thought so too) but, in fact is 0 (assuming a UA with spec compliance).
- Code: Select all
opt = opts["blah"] ;
opt.index <-- returns 0
opt = opts[1]
opt.index <-- returns 0
However, if one takes the datalist's options collection as a starting point (options => HTMLCollection) then one *can* retrieve a given nth option element using an index and at the same time be refused its index:
- Code: Select all
var opts = document.getElementById("myDL").options;
alert(opts.item(3).index + " = " + opts.item(3).value);
To save you time, the above renders: -1 = three
(Tested: Firefox 12 and, if I've read everything correctly, is perfectly (but laughably) correct).
Where the spec is at fault (IMO): It talks about "list of options" and defines them as differing between lists of options belonging to a select element and lists of options belonging to a datalist element. Why? To what end? For what meaningful purpose? The crazy thing is, to conform, UAs will be writing extra and unnecessary code just to comply. Notionally:
- Code: Select all
function getOptIndex(opt) {
if my parent is a datalist
return 0;
else
return opt.index;
}
IMO, a datalist should be "a list" and behave as "a list". i.e. as any "common man" might expect: a list has implied order and the order is (should/must) be discoverable (please, check your OL and UL baggage at the door
Ruzz