Home > Blockchain >  Triggering event click() using document.querySelector() is not working, but triggering CSS event cli
Triggering event click() using document.querySelector() is not working, but triggering CSS event cli

Time:11-21

Triggering event click() using document.querySelector() is not working, but triggering CSS event click() from console works ok as follows:

$0.click(); // Works Ok

$0 refers to the same element that document.querySelector()

const element = document.querySelector('.red')
element.click(); // Not Works

element:

<span color="foreground" class="red">Red</span>

$0:

<span color="foreground" class="red">Red</span>

How could click in the element using document.querySelector()?

CodePudding user response:

Does it work ?

First of all, please note that triggering $0.click() in the console is not CSS but Javascript.

Also, calling your element with a querySelector and then triggering the click method works fine. Here is a basic example :

setInterval(() => {
  document.querySelector('.red').click()
}, 1000)
<span class="red" onclick="console.log('clicked')">Text in a span</span>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Why it could fail

You nay face different situations where your code do not works as you expected.

1- You may call your script before the page finished loading. In this case, the reference to document.querySelector will not find the element, and return null instead of the element. But when this happens, we get an error in the console.

2- You have several elements in your page with the class of "red". Then, you are probably clicking on an other element. In this case, nothing appears in the console.

  • Related