views:

100

answers:

2

If jQuery is included in <head> and in <head> if we have some another jQuery code and that code has an id which is a id of an HTML element, so if jQuery library and jquery code in <head> is added globally

And if any page doesn't have that html element which is used by jQuery code then browser gives JavaScript error.

Can I make jQuery/JavaScript code like, if jQuery finds an HTML element with id in <body> then it should work fine.

If another page doesn't have that HTML element with id then I know jQuery will not work.

But what I want:

An error should not be thrown if a page doesn't have an HTML element with the given id.

+5  A: 

A lot of jQuery code works like this already, as it is set-based, and you can do operations on sets of 0 elements. I.e. these will always work, regardless of whether or not the selector matches any elements:

$('#myButton').click(function() { ... });
$('#somethingElse').hide();

In some cases you really do need a reference to at least one element, however, for the rest of the script to work. In these cases, you have to manually check that the element exists:

if($('#myElement').length == 0) return false; // or similar...
David Hedlund
@David - can u explain with example?
metal-gear-solid
`if($('#myElement').length) { ... }` Shorter and does the same thing
Erik
@Jitendra: that was my example! `$('#myElement')` is jQuery code to find all elements with the id "myElement". as it is an array(ish) of elements, you can check its `length` property. if length is 0, it means there was no element with the id "myElement" in the page. Since 0 is *falsy* i.e. resolves to false when used as a boolean, Erik's shorter version is exactly equal.
David Hedlund
+1  A: 
if($('#myElement').length != 0){
  my special js magic thing;
}else{
  return false;
}
Eduplessis