开发者

select by id in jquery

as all you know

$("#ID")  

returns the element having ID.

but this code always return even there's no element.

alert($("#htrBuyerCouponNotice"));
alert(docu开发者_StackOverflow中文版ment.getElementById("htrBuyerConponNotice"));

in this case.

those two line results are diffrent.

I want to check whether there is an element has htrBuyerCouponNotice.

document.getElementByID return null if there's no element.


You can check the length property of the jQuery object to determine the number of matched elements, e.g.:

alert($(selector).length);

You can use it directly on if statements e.g.:

var $el = $(selector);

if ($el.length) { // only 0 will coerce to false
  // ...
}

But most of the time you don't really need to know if the selector matched elements or not, because the jQuery built-in methods will be simply ignored, e.g.:

$('#nonExistent').hide();

The above statement will not cause any error even if the element was not found.

jQuery has also the size method, but I would recommend you to use the length property directly since it's publicly accessible, the size method is slightly slower since it is only a function that returns the value of length property.


because jQuery returns a list of selected elements, if there are no elements, you still get a return - its just a empty list.

check for $('#someID').length - should work if i remember corretly


When selecting elements, jQuery will always return an array of matching elements. In your case, $('#htrBuyerCouponNotice') is probably returning an empty array. Instead, check $('#htrBuyerCouponNotice').length.

Andrew


Try:

$("#htrBuyerCouponNotice").size()

It'll be zero if there's no nodes with that identifier, 1 if there is.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜