Return the value that is clicked from an array in a Function. I only know how to do using Event.target

Asked

Viewed 84 times

1

I want to return the value that is clicked, from the array. I know how to do this only with add.Eventlistener. In the case e.target.

<h2 onclick="menuclick()" class="notselectable btnmenu">a</h2>
<h2 onclick="menuclick()" class="notselectable btnmenu">b</h2>
<h2 onclick="menuclick()" class="notselectable btnmenu">c</h2>
<h2 onclick="menuclick()" class="notselectable btnmenu">d</h2>



function menuclick() {
    const btnmenu = document.getElementsByClassName('btnmenu');
    Array.from(btnmenu).forEach(function (item) {
        console.log(target);

    })
}
item is not defined;
(Quero que retorne 'a' se clicado no 'a'. wtc)


  • I thought to put onload instead of on click on html, and put an Event addeventlistener('click') inside the function. I don’t know if it’s wrong

1 answer

1


This is very simple. Two steps:

  • if you pass the this inside onclick="menuclick()" you have the element you clicked.
  • then just extract the text with (for example) .textContent

function menuclick(h2) {
  const texto = h2.textContent;
  console.log(texto);
}
<h2 onclick="menuclick(this)" class="notselectable btnmenu">a</h2>
<h2 onclick="menuclick(this)" class="notselectable btnmenu">b</h2>
<h2 onclick="menuclick(this)" class="notselectable btnmenu">c</h2>
<h2 onclick="menuclick(this)" class="notselectable btnmenu">d</h2>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.