-1

I am trying to add onclick properties to multiple buttons using DOM. langButton.onclick = searchEngine(langButton); does not add the property to the button and eventListener does not work either. I need to read the text of the specific button that is clicked, or just copy the button all together. Here is the code block:

for (j = 0; j < applications[i].languages.length; j++) {
  let langButton = document.createElement('button');
  langButton.classList.add('btn-secondary');
  langButton.innerHTML = `${applications[i].languages[j]}`;
  langButton.onclick = searchEngine(langButton);
  // console.log(langButton.innerHTML);
  langDiv.appendChild(langButton);
}

btn-secondary is a Bootstrap class.

function searchEngine(button) {
  return button
}

returns the button, but runs each time it tries to set the onclick property. Then the buttons do not return anything after being clicked. The console.log(langButton.innerHTML) returns the button's text just fine.

  • 1
    `onclick` expects a function; `searchEngine(langButton)` isn’t a function. Also, use [event delegation](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of assigning multiple event listeners — it’s more maintainable, and applies to dynamically added elements. E.g., use an [event argument](//developer.mozilla.org/docs/Web/API/EventTarget/addEventListener#The_event_listener_callback)’s [`target`](//developer.mozilla.org/docs/Web/API/Event/target). See [the tag info](/tags/event-delegation/info) and [What is DOM Event delegation?](/q/1687296/4642212). – Sebastian Simon Aug 20 '21 at 00:14
  • 1
    The line `langButton.innerHTML = \`${applications[i].languages[j]}\`` can be shortened to langButton.innerHTML = applications[i].languages[j] – Rojo Aug 20 '21 at 00:14

1 Answers1

1

An event listener has to be a function. You're calling the function, not assigning the function.

langButton.addEventListener("click", () => searchEngine(langButton));
Barmar
  • 741,623
  • 53
  • 500
  • 612