In my attempt to attach onclick functionality to multiple buttons using DOM manipulation, I have encountered some challenges. The line
langButton.onclick = searchEngine(langButton);
fails to add the property to the button and utilizing an event listener also does not yield the desired result. My goal is to extract the text of the specific button that gets clicked or simply clone the entire button altogether. Below is the snippet of code in question:
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);
}
The 'btn-secondary' class belongs to Bootstrap.
function searchEngine(button) {
return button
}
While the current implementation successfully returns the button, it unfortunately executes each time it attempts to set the onclick property. As a consequence, the buttons cease to function after being clicked. Conversely,
console.log(langButton.innerHTML)
effectively retrieves the text content of the button without any issues.