Reputation: 9
I need a button that changes the class of different elements, I tried this this way :
<button id="class-button">class change</button>
<div id="title">this is the title</div>
<script>
document.getElementById("class-button").addEventListener("click", () => {
document.getElementById("title").event.target.classList.add("the-class")
}
</script>
and that failed.
Upvotes: 1
Views: 765
Reputation: 52
So I see two issues with your code:
You don't need the .event.target as you are not looking for an event. This means you can remove the .event.target
.
Also you have not closed your event listener which means it's missing the closing bracket (which causes syntax errors).
The solution would be:
document.getElementById("class-button").addEventListener("click", () => {
document.getElementById("title").classList.add("the-class");
});
body {
font-family: sans-serif;
}
.the-class {
color: blue;
}
<h1 id="title">Keep on coding!</h1>
<button id="class-button">Change To Blue</button>
Upvotes: 1
Reputation: 4068
Maybe you could put your JS in the onclick parameter.
<input type="Button" value="Click Me" onclick="document.getElementById('YourId').classList.add('className');" />
Upvotes: 0
Reputation: 31987
There is no event
property of an HTMLElement
.
If you want to add a class to the element, get rid of the event.target
and do simply:
.the-class{
color:red;
}
<button id="class-button">class change</button>
<div id="title">this is the title</div>
<script>
document.getElementById("class-button").addEventListener("click", () => {
document.getElementById("title").classList.add("the-class");
})
</script>
Upvotes: 0