Decoda

Decoda is a lightweight lexical string parser for BBCode styled markup.

Checking if an element exists

Friday, June 12th 2009, 12:36am
Topics: Javascript, Tutorials
Tags: Javascript, Element, Exists
Comments: 5
Permalink - Tinylink

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) {
	var el = document.getElementById(id);
	
	if (el != null) {
		return true;
	}
	
	return false;
}

if (elementExists('column')) {
	// Column exists
}
Related Entries:

5 Comments

10 / 2 = ?
Allowed: [code] [b] [i] [u]
  • Richard@Home
    richardathome.com
    Jun 12th 2009, 03:12
    1 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
    }
  • RafaƂ Filipek
    rafal-fili...ogspot.com
    Jun 12th 2009, 21:52
    2 much easier ( smaller ) way:
    function elementExists(id){
    return document.getElementById(id) ? true : false;
    }
  • Miles Johnson
    milesj.me
    Jun 13th 2009, 03:25
    3 Thanks you guys.

    @Rafal - Yeah it could of been shortened, just kept it that way for beginners.
  • Vasili
    vasili.duove.com
    Jul 16th 2009, 11:59
    4 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!
  • Dimitar Christoff
    fragged.org
    Feb 1st, 15:39
    5 @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 :)