Sungguk Lim
Sungguk Lim

Reputation: 6218

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(document.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.

Upvotes: 0

Views: 385

Answers (4)

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827238

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.

Upvotes: 3

Andrew
Andrew

Reputation: 2230

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

Upvotes: 1

Ken
Ken

Reputation: 691

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

Upvotes: 1

Dean Harding
Dean Harding

Reputation: 72648

Try:

$("#htrBuyerCouponNotice").size()

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

Upvotes: 0

Related Questions