George D
George D

Reputation: 19

Checkbox not clickable with javascript. .click() is not a function

I've tried automating a checkbox to click with JavaScript, in Google Chrome.

This is what the inspector of the browser shows me when I inspect the checkbox:

<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-square" data-icon="Square" aria-hidden="true" focusable="false"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect></svg>

This is how I've tried to click the button:

document.getElementsByClassName('lucide lucide-square')[0].click();

It does recognise the element but it doesn't click it.

It returns the error:

VM3971:1 Uncaught TypeError: document.getElementsByClassName(...)[0].click is not a function
    at <anonymous>:1:60

Anybody can help with this, please?

I've tried also .onclick or also to call the element with querySelector, but it doesn't work.

I was expecting the checkbox to work like other ones on the same website, which were all clickable with .click()

Upvotes: 0

Views: 452

Answers (2)

George D
George D

Reputation: 19

So I'm posting the answer of @LouysPatriceBessette, which worked for me

document.getElementsByClassName('lucide lucide-square')[0].parentElement.click()

Upvotes: 1

Michael M.
Michael M.

Reputation: 11080

The element you're trying to click isn't actually a button, it's an <svg> element that looks like a button but is really more like an image. Only real buttons have the .click() method, however you can artificially fire the click event by creating a new event with CustomEvent and sending it to the button:

const btn = document.getElementsByClassName('lucide lucide-square')[0];

// example event handler
btn.addEventListener('click', function() {
  console.log('clicked');
});

var event = new CustomEvent('click');
btn.dispatchEvent(event);
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-square" data-icon="Square" aria-hidden="true" focusable="false"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect></svg>

Upvotes: 1

Related Questions