Skip to content

Instantly share code, notes, and snippets.

@mojaray2k
Created September 9, 2013 01:37
Show Gist options
  • Save mojaray2k/6490399 to your computer and use it in GitHub Desktop.
Save mojaray2k/6490399 to your computer and use it in GitHub Desktop.
By now you are probably used to checking the length property of jQuery objects to determine whether the element you attempted to select exists. The following trick will make your code a bit more expressive and easier to read:
<!DOCTYPE html>
<html>
<head>
<title>jQuery Exists Function</title>
</head>
<body>
<div id="elem"></div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<meta charset=utf-8 />
</body>
</html>
// Old way
console.log($('#elem').length == 1 ? "exists!" : "doesn't exist!");
// The trick:
jQuery.fn.exists = function(){ return this.length > 0; };
console.log($('#elem').exists() ? "exists!" : "doesn't exist!");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment