jQuery Check If an Element Exists


Without any JavaScript library, if you want to check whether an element exists, in our case, an element with the id myDiv, here is what you do:

<script>
if (document.getElementById('myDiv')) {
    alert('myDiv exists');
}
</script>

In jQuery, here is what you can do:

<script>
if ($('#myDiv').length) {
    alert('myDiv exists');
}
</script>
Share and Enjoy:
  • Print this article!
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Technorati
  • Twitter
  • Yahoo! Bookmarks

  1. No comments yet.
(will not be published)