Tag cloud
See my latest projects
About this site
This site is proudly powered by WordPress. If you like what you see, why not subscribe?
Copyright © 2008-2009 Aaron Russell. All rights reserved.
Monday, 15 September 2008
When using jQuery (or any other JavaScript library for that matter), have you ever wondered how to test whether an element exists using a selector? Well, maybe you haven’t, but I have – lots of times – so I thought I’d share how it’s done here because it’s not as simple as it seems.
The obvious thing would simply be to wrap a selector in an if statement, right?
if ($("#mydiv")){ // do something here }
Well, wrong – that won’t work! When you use a selector, jQuery will always return an object. Therefore the if statement will always be true and never be false. In the case of an element that does not exist on the page, jQuery will return an object with nothing in it – an empty object. And therein lies our solution.
With a jQuery selector we can also use the length property, which will return the size of the object. Do you see where I’m heading with this? That’s right, lets just change our if statement to:
if ($("#mydiv").length > 0){ // do something here }
Now our code works because when jQuery returns an empty object, the length property will return zero and therefore the if statement will be false. Hurrah!
// this works too..
if ($(”#mydiv”).length){
// do something here
}
That’s true Tiago – cheers for sharing. I’ll leave my explanation as it is because I think the “greater than zero” operator illustrates why it would return true or not. But you solution is slightly more elegant
You could also use
if($(”#mydiv”).size()) {
//do something
}
Thx mate, just the thing i was looking for. Keep it up!
With the advent of modern browsers and full page zooming I take a look at the issue of relative versus absolute font sizing and whether it’s time to think again.
Having been using ExpressionEngine for a few weeks now, I offer my first impressions and try to answer whether it is the perfect CMS.
Here are five tips designers should follow to make developers’ lives easier and so that everyone can live together in web design harmony.
I’ve begun using AudioBoo, a service that allows you to record short sharp audio podcasts – think Twitter for audio. Despite still finding the sound of my own voice somewhat cringe-worthy, I’m rather enjoying it.
I am delighted announce the launch of brownnosefriday.com, the first web application to recognise and reward Twitter’s top brown nosers.
“@wizely suberb idea, aaaaaaah, I love working from home http://twitpic.com/91sf8”
Posted about 9 hours ago.
This site is proudly powered by WordPress. If you like what you see, why not subscribe?
Copyright © 2008-2009 Aaron Russell. All rights reserved.