8

I have a .js file that is invoked by a few .jsp pages. What I need to do in this particular .js file is to invoke a certain function only if the 'save' button is present in the .jsp page. How do I check if the button exists? Currently, in the .js file the button is referred to this way: $('button[id=save]')

How do I check if such a button exists?

Georgy
  • 12,464
  • 7
  • 65
  • 73
John Java
  • 153
  • 1
  • 3
  • 8
  • 1
    you can also look into this post http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery – pappu_kutty Nov 19 '13 at 07:12
  • possible duplicate of [Check if element exists in jQuery](http://stackoverflow.com/questions/4592493/check-if-element-exists-in-jquery) – Voonic Nov 19 '13 at 07:14

2 Answers2

19

try something like this

$(document).ready(function(){
    //javascript
    if(document.getElementById('save')){
        //your code goes here
    }
    
    //jquery
    if($('#save').length){
        //your code goes here
    }
});
Georgy
  • 12,464
  • 7
  • 65
  • 73
rajesh kakawat
  • 10,826
  • 1
  • 21
  • 40
  • 1
    +1 `getElementById` is enough, you could remove the jQuery part :) –  Nov 19 '13 at 07:20
4

You can do this:

if($('#save').length > 0){
    // Button exists
} else {
    // Button is not present in the DOM yet

}
palaѕн
  • 72,112
  • 17
  • 116
  • 136