Elijah
Elijah

Reputation: 9

how to make a button that changes the class of another element?

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

Answers (3)

Dev Jason Clarke
Dev Jason Clarke

Reputation: 52

So I see two issues with your code:

  1. You don't need the .event.target as you are not looking for an event. This means you can remove the .event.target.

  2. 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

SteinTech
SteinTech

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

Spectric
Spectric

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

Related Questions