Checking if an element exists

So with my new design, I wanted a way to keep all columns around the same height, especially so the middle doesn't look awkward. To do this, I was going to use JavaScript and get the heights of each column and then calculate. A problem was that some pages do not have the right column, so I had to test to see if the column existed. To do that, all you use is the getElementById().

var el = document.getElementById('column');
if (el != null) {
	// Column exists
}

Easy enough now isn't it. I'm not exactly sure how this is done in jQuery, as I couldn't find an answer in the documentation. It is probably done with some selector and traversing magic. Now, to make things easier, we can package this into a function to be reused over and over.

function elementExists(id) {
	return document.getElementById(id);
}
if (elementExists('column')) {
	// Column exists
}

5 Comments

  • @rafal - shorter coercion.

    ElementExists = function(id) {
        return !!document.getElementById(id);
    };
    

    if you don't care about ie7/8 then Element.exists is fine in the Native Type.

    Doing a double check to the dom is expensive, just look at the HTML collection length in the jquery wrapper. or don't use jquery
    Dimitar Christoff ⋅
  • The only thing that I see that isn't good practice is the fact that you'll be using the document.getElementById method twice. I would prefer to write out element != null than call a function whose name is longer than the expression!
  • Thanks you guys.

    @Rafal - Yeah it could of been shortened, just kept it that way for beginners.
  • much easier ( smaller ) way:
    function elementExists(id){
    return document.getElementById(id) ? true : false;
    }
  • In jQuery $() returns an array of matching elements, so you can test the size of the array to check if an element exists:

    if ( $("#idImLookingFor").length > 0 ) {
    // element exists
    }