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 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
}
Are you having trouble with your excerpts? Is WordPress misbehaving and making your them look below standard when all you want to do is use it’s native excerpt function? You’re not alone so read on.
Every once in a while I come across something that just makes me smile. Today it comes in the form of an advertisement for the German energy firm, Epuron. Watch it here.
SEO consultant Eggman John recently posted an article outlining seven reasons why you don’t need SEO. John’s article caused a stir amongst the SEO community, but read why I think there is a lot of sense in what he says.
When flicking through my feeds I came across this clever little poster campaign by Russian Bear Vodka, explaining why real men don’t drink and drive in a subtly clever way.
The CSS ‘display’ property is definitely a bit more complicated than it should be. In this article I will show a quick and simple way to get the display:inline-block declaration rendering consistently across all major browsers.
This site is proudly powered by WordPress. If you like what you see, why not subscribe?
Copyright © 2008 Aaron Russell. All rights reserved.