Created
September 9, 2013 01:37
-
-
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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