Getting An Error "cannot Read Property 'click' Of Undefined" If Selector Or Class Cannot Be Found In The Dom
Solution 1:
As I understand, you want to call the click event on that specific element dynamically through your code.
Your $('.trigger-pdf') doesn't exist at the time you call .click()
So first, you need to make sure it exists by something like this:
if ($.type($('.trigger-pdf')) !== 'undefined' && $('.trigger-pdf').length > 0) {
$('.trigger-pdf').trigger('click');
}
If your element (.trigger-pdf) is something that was dynamically added to the DOM, then binding an event with .on() wouldn't help you. You need to use dynamic binding as follows:
$('body').on('click','.trigger-pdf',function() { // Do your stuff here...});
Instead of $('body'), refer to something that is physically there when your code runs.
Solution 2:
You can make your code more robust by using
$('.trigger-pdf').eq(0).click()
which won't trigger any errors if the element doesn't exist.
See https://api.jquery.com/eq/
You should figure out why that appears to be the case though. Perhaps you should be wrapping your code in a document ready event handler, ie
jQuery(function($) {
$('.trigger-pdf').eq(0).click()
})
Solution 3:
Always use on() to bind events
$('static_element').on('click', '.dynamic_element', function() { // code });
Post a Comment for "Getting An Error "cannot Read Property 'click' Of Undefined" If Selector Or Class Cannot Be Found In The Dom"