开发者

jQuery object as a array: $('#id')[0]; [duplicate]

This question already has answers here: jQuery Object array notation (2 answers) 开发者_JS百科 Closed 8 years ago.

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]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜