I am working on a website and I want that when the user clicks on a specific card, it turns blue. I have searched and found some things online, but it is not working for me and I don't know why; here is the code:
<div class="card" onclick="myFunction()">
<p class="number-card">1</p>
</div>
<script>
function myFunction() {
document.getElementById("card").style.backgroundcolor = "blue";
}
</script>
document.querySelectorAll(".card") MDN querySelectorAllbackgroundColor with capital Con* attribute handlers. JS and styles should always be in their respective tags or files, not disseminated around a HTML file.<div class="card">
<p class="number-card">1</p>
</div>
<div class="card">
<p class="number-card">2</p>
</div>
<script>
const changeBgColor = (ev) => {
ev.currentTarget.style.backgroundColor = "blue";
};
const EL_cards = document.querySelectorAll(".card");
EL_cards.forEach(EL => EL.addEventListener("click", changeBgColor));
</script>
Alternatively, using a regular function (where addEventListener binds by default this to the Event.currentTarget Element):
function changeBgColor() {
this.style.backgroundColor = "blue";
}
You only have the class set to card but you're trying to getElementById, you should give the div an id that's unique and change the function.