I have encountered a challenging situation where I am using JavaScript to render data from a data.json file into HTML. Everything seems to be functioning correctly, as the JSON data is being successfully rendered into HTML using a loop, resulting in multiple objects with the same class.
However, due to this setup, every button I create ends up belonging to the same class within the loop. Now, here's my dilemma: I want to hide only the specific button that is clicked, not all buttons of the same class.
var X = document.getElementsByClassName("buttons");
function HideClickedButton() {
for (let x of X) {
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
}
for (const button of X) {
button.addEventListener('click', HideClickedButton);
}
<button class="buttons">Test</button>
<button class="buttons">Test</button>
<button class="buttons">Test</button>
<button class="buttons">Test</button>
The code above currently hides all buttons with the same class when one is clicked.
If I use just
document.querySelector(".buttons").style.display = "none"
,
it always hides the first button regardless of which button is pressed.
Edited Section:
<div onclick="addToCart(${product.price})">
<button class="b1" onclick="hideAddButton(this)" type="button">ADD</button>
</div>
<div onclick="addToCartRemove(${product.price})">
<button class="b2 hidden" onclick="showRemoveButton(this)" type="button">Remove</button>
</div>
My JavaScript code looks something like this, where I am rendering a list from JSON. After rendering, there are a total of 12 buttons. They are grouped in sets of 6 (see image). Now, I do not want to initially display the remove button. It should only appear when the corresponding ADD button is clicked. Upon clicking the ADD button, it will disappear and the Remove button will take its place, while the other ADD buttons remain visible. Please let me know if you understand.https://i.stack.imgur.com/8A5Ht.png