Episode 10: If an Element Exists

How to tell if an element exists

When you’re working with jQuery, sometimes you need to figure out if an element that you’re trying to select actually exists on the page. You’d think this would be simple and straightforward, but there’s actually a little trick to it that I’ll share with you in this video.

We get started with a list of animals – one of them has a class of highlighted and elsewhere on the page, we want to create a little callout to put the highlighted animal in the spotlight.

We get started by adding a new element to the page using skills that we learned in Episode 3. Then we just add a few quick styles to the new element in CSS just so that we can see it on the page.

Next, we learn how to use jQuery text() method, both to add text to our new element and to fetch the text from another element. This works great as long as there’s an element on the page with the class of highlighted, but if it doesn’t exist, the page looks odd. We want to set up some different text if the highlighted class is missing from the page.

We talk just a bit about JavaScript and how to test if things are true. Many values in JavaScript aren’t actually strictly true or false, but rather truthy or falsey – in a sort of gray area. If a variable is empty and I test it, it returns falsey. Which means that if we test the variable where we used our selector, it should return falsey since it’s empty, right?

Well, not with jQuery. Because if a variable holds a jQuery selector, that variable is never actually empty because it holds a jQuery object. The jQuery object might be empty, but the variable doesn’t know that. It just knows it’s got a jQuery object so it returns a truthy value.


Think of a jQuery object like a box. A box isn’t nothing – it’s definitely something. If you’re holding a box, then you’ve definitely got something in your hands. Now, that box might be empty or it might have a kitten or a pie in it. Either way, you’ve got something in your hands.

That’s how a jQuery object works. The jQuery object is something, even when it’s empty. So to test if an element that we’re trying to select is actually on the page, we have to test if the jQuery object is empty or not, not the variable where we used our selector.

We can test that by using the length property of the jQuery object to see if there’s anything in the box. If the length is greater than 0, then the box contains something. Otherwise, the box is empty.

Tags: , , ,

No Responses to “Episode 10: If an Element Exists”

  1. Dave January 8, 2015 at 8:45 am #

    Very cool vid, thanx. I wanted what would happen if there were multiple items with the class highlighted. My guess is that the text would be concatinated.

Leave a Reply