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().
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.
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
}
5 Comments
richardathome.com
Jun 12th 2009, 03:12
if ( $("#idImLookingFor").length > 0 ) {
// element exists
}
rafal-fili...ogspot.com
Jun 12th 2009, 21:52
function elementExists(id){ return document.getElementById(id) ? true : false; }milesj.me
Jun 13th 2009, 03:25
@Rafal - Yeah it could of been shortened, just kept it that way for beginners.
vasili.duove.com
Jul 16th 2009, 11:59
fragged.org
Feb 1st, 15:39
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 :)