Is this a valid jQuery syntax :$('#id')[0];
To retrieve a single element from a jQuery object:
$("div")[0]
which is short for:
$("div").get(0)
A jQuery object can be used largely as an array because it also supports a property of length
but if you want an actual array:
var arr = $("div").get();
Yes, but #id
will get you a single object (at most) anyway.
Also, note that [0]
will get you the DOM element, not a jQuery object, so you can't use jQuery's function without wrapping it again.
Yes it is valid. It retrieves the first element of the array of matched elements by the selector. As you are selecting by id which is supposed to be unique in the DOM your selector would normally return at most one element. But if no element is matched this code will fail.
You don't have to do like this. In a properly valid document there will be only one element with an id. So document.getElementById
will return only a single element.
For any other selector you can use this syntax
For example when using a class selector
$(".classname")[0]
精彩评论