Seth is currently live on Twitch! Go There Now?
October 29, 2019
Advice I Wish I Could Take For Myself
Using JQuery To See If An Element Exists

To see if an element exists, the easiest way is to count how many elements of that type are on the page. Use the .length property of the jQuery collection returned by your selector:

  • <div></div>
  • <script>
  • if($('div').length){ //-> if div has a length, ie: has more than zero instances
  • //-> do whatever you needed to do if the element exists
  • }
  • </script>

The length property will count how many elements of that type exist. So if $( "#myDiv" ).length exists, then there must be more than zero of them, otherwise it would return false (zero).

I do this for many different reasons. Usually I'm browsing through many elements that are the same, and only using jQuery to affect the elements that have a child that exists, or doesn't exist.

For example, the top part of this website has the animated background that will change as you browse through this website. That image that's up top is dependent on what page you're on, but I use jQuery to see whether or not the image exists before replacing it. That way, if the correct image is already up there, I don't erase it just to put it back up. I leave it there to ensure a better browsing experience for the end-user. This also allows that animated background to continue animating as I browse through the site without it starting back at the beginning of the animation. As you change pages, the top banner doesn't reload, it stays put. This is a very subtle thing but I think it looks very nice.

 Profile Picture
Comment