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?
To check the presence of an element, we can use the method – findElements. The method findElements returns a list of matching elements. Then, we have to use the method size to get the number of items in the list.
In jQuery, you can use the . length property to check if an element exists. if the element exists, the length property will return the total number of the matched elements.
length){ alert('Found with Length'); } if ($('#DivID'). length > 0 ) { alert('Found with Length bigger then Zero'); } if ($('#DivID') != null ) { alert('Found with Not Null'); } }); Which one of the 3 is the correct way to check if the div exists?
try something like this
$(document).ready(function(){
    //javascript
    if(document.getElementById('save')){
        //your code goes here
    }
    
    //jquery
    if($('#save').length){
        //your code goes here
    }
});
                        You can do this:
if($('#save').length > 0){
    // Button exists
} else {
    // Button is not present in the DOM yet
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With