web design and coding services with a huge twist of creativity.

Stuff Tagged ‘DOM’

A step towards unobtrusive Javascript

Published 2 years ago, in Blog, Web

Unobtrusive Javascript

Separating content from behaviour

When incorporating Javascript behaviour on your pages, you’ll probably want to take advantage of mouse events to trigger certain functions. The most obvious and common example is to display a small modal window when a user clicks a given link on the page. (…) more after the jump ›

jQuery tip: Check if an element exists

Published 2 years ago, in Blog, Web

It’s a very common question for people starting out with jQuery: How do I know if element X exists? There is no standard function for you to use, however, it’s really simple to write one yourself.

What you’ll probably try to do first is to perform a check on a jQuery object, like this:

//This won't work :(
if ( $("#myId") ) {
  //awesome code here
}

The reason this method doesn’t work is that when you use the $(), you’re asking for a jQuery object. You always get a jQuery object, even if it’s an empty one. Thus, the above code always returns true, and that’s just sad.

However, the object returned by jQuery will have an internal array filled with all the elements that do match your selector. You can access this internal list’s length using the .length property. This means that, if the length of your object is greater than zero, your element does indeed exist in the DOM. Putting that into code, we get:

//This works, yay!
if ( $("#myId").length > 0 ) {
  //awesome code here
}

Although the examples shown here only checked for the existence of an element with a certain ID attribute, you can obviously use this technique with any jQuery selector you wish.