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
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
@Rafal - Yeah it could of been shortened, just kept it that way for beginners.
if ( $("#idImLookingFor").length > 0 ) {
// element exists
}