1

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.

Elijah
  • 15
  • 8
  • What errors are you seeing in your developer console? Can you elaborate on how you reached the conclusion (or provide a link to the source on which you're basing your implicit claim that) that the [`Element`](https://developer.mozilla.org/en-US/docs/Web/API/Element) returned from [`document.getElementById()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById) should have an `event` property? Better yet, what do you believe `document.getElementById("title").event.target` should return? Why not just `document.getElementById("title").classList.add("the-class")`? – esqew Jul 13 '21 at 16:44
  • @esqew I am a beginner – Elijah Jul 13 '21 at 17:02

3 Answers3

1

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>
0

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>
Spectric
  • 30,714
  • 6
  • 20
  • 43
0

Maybe you could put your JS in the onclick parameter.

<input type="Button" value="Click Me" onclick="document.getElementById('YourId').classList.add('className');" />
SteinTheRuler
  • 3,549
  • 4
  • 35
  • 71
  • Generally this is a stylistic choice, but using `on*` attributes on HTML elements is largely considered to be not preferable to [unobtrusive JavaScript](https://stackoverflow.com/questions/5871640/why-is-using-onclick-in-html-a-bad-practice). – esqew Jul 13 '21 at 16:58
  • True. I just sometimes like it to keep the code minimal. But off course having all the code in a external file is probably better – SteinTheRuler Jul 13 '21 at 17:44