Checking if a dom element exists with JQuery [Byte sized tips]

This is a simple tip but one I feel makes my code a bit easier to read. I was never very pleased with the standard way of checking if a dom element exits in jquery: if($('#userName').length !== 0){ //do something with $('#firstName') } The solution I like is to create a very simple jQuery plugin to encapsulate this logic: // this extension reads better when selecting elements $.fn.exists = function () { return this ....

June 25, 2012 · 1 min · Brandon Pugh