0

I want one item to be clicked when I click on a different one, but I keep seeing these complicated answers that, frankly, don't make any sense. I feel like it should be easy as this, but this doesn't work.

<div class="myElement" onclick="myFunction()"></div>
<a href="https://example.com" class="myElement2"></a>
function myFunction() {
  document.getElementsByClassName('myElement2').click();
}
Alexander
  • 131
  • 9

1 Answers1

0

There're some points you need to know:

  1. getElementsByClassName returns an array
  2. there have to be something in the <div>, otherwise it's height is 0px, so you have no where to click

try this one:

<script>
function myFunction() {
    for (let e of document.getElementsByClassName('myElement2')) {
        e.click();
    }
}
</script>

<div class="myElement" onclick="myFunction()">
    hello
</div>
<a href="https://example.com" class="myElement2"></a>
z7z8th
  • 3
  • 3