Reputation: 351
I have a button on a webpage with the following inspection:
<button type="button" class="odd-item-dropdown-confirm" data-qa="button-odd-item-dropdown-confirm">Confirm</button>
I would like to click on this button, I tried:
function clickConfirm(){
var bntConfirm = document.querySelector('.btn.button-odd-item-dropdown-confirm');
bntConfirm.click();
}
clickConfirm();
And got Uncaught TypeError: Cannot read property 'click' of null
Upvotes: 3
Views: 133
Reputation: 669
Your selected class is not the correct one.
clickConfirm();
function clickConfirm(){
var bntConfirm = document.querySelector('.odd-item-dropdown-confirm');
bntConfirm.click();
}
Upvotes: 1
Reputation: 4346
this is a problem in your code:
var bntConfirm = document.querySelector('.btn.button-odd-item-dropdown-confirm');
you don't have .btn
class anywhere
you don't have .button-odd-item-dropdown-confirm
class anywhere
Take a look at the solutions that can work
clickConfirm();
function clickConfirm(){
// this will not work.
// var bntConfirm = document.querySelector('.btn.button-odd-item-dropdown-confirm');
// you don't have .btn class anywhere
// you don't have .button-odd-item-dropdown-confirm class anywhere
/* --------------------- */
// select by class
var bntConfirm = document.querySelector('.odd-item-dropdown-confirm');
bntConfirm.click();
// or select by data attr
var bntConfirm = document.querySelector('*[data-qa="button-odd-item-dropdown-confirm"]');
bntConfirm.click();
}
<button type="button" class="odd-item-dropdown-confirm" data-qa="button-odd-item-dropdown-confirm">Confirm</button>
Upvotes: 1
Reputation: 497
clickConfirm();
function clickConfirm(){
var bntConfirm = document.querySelector('.odd-item-dropdown-confirm');
bntConfirm.click();
}
I think this should work if you haven't used this class anywhere else, but you can always use Ids, or other things to identify the button properly.
Upvotes: 2
Reputation: 66123
It says what it means: the query is not matching any element and returning null
. If you look at your HTML, there is no class button-odd-item-dropdown-confirm
.
You should be selecting using this selector: button.odd-item-dropdown-confirm
. See proof-of-concept:
// Checking
document.querySelector('button').addEventListener('click', () => {
console.log('I am clicked');
});
clickConfirm();
function clickConfirm(){
var bntConfirm = document.querySelector('button.odd-item-dropdown-confirm');
bntConfirm.click();
}
<button type="button" class="odd-item-dropdown-confirm" data-qa="button-odd-item-dropdown-confirm">Confirm</button>
Upvotes: 7