1

I would like to change the class of HTML elements without the use of the ID tag because I have so many of these elements. I would like to have something simple like this but the code is not working.

<li ><a onclick="ChangeClass()" href="/Default.aspx">Home</a></li>

<script>
        function ChangeClass(){
            this.className = "active";
        } 
</script>

EDIT: Sorry, That was a type. My code did have the brackets but still isn't working.

EDIT2: Thanks for the quick replies, I will look at all of them and take notes.

anderish
  • 1,709
  • 6
  • 25
  • 58
  • You can use the [element/document.querySelectorAll()](https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll) API to get a list of all those elements that you want to fiddle with their `className` or `classList` property. – Redu Dec 21 '16 at 16:18
  • 1
    I'd say you need onclick="ChangeClass(this)" and then function ChangeClass(elm) {elm.className=.....} – Tony Duffill Dec 21 '16 at 16:21
  • 1
    `this` does not mean what you think it does there – Liam Dec 21 '16 at 16:21
  • 1
    Possible duplicate of [How to get the onclick calling object?](http://stackoverflow.com/questions/1553661/how-to-get-the-onclick-calling-object) – Liam Dec 21 '16 at 16:22
  • Lexical this. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this – briosheje Dec 21 '16 at 16:22

2 Answers2

5

'this' here is pointing to window object. you can use call/apply to change the context of this.

check this snippet

 function ChangeClass(event) {
   this.className = "active";
 }
.active {
  color: red;
}
<li><a href="/Default.aspx" class="default" onclick="ChangeClass.call(this)">Home</a>
</li>

<script>
</script>

Hope this helps

Geeky
  • 7,420
  • 2
  • 24
  • 50
  • you don't need the `.call()` `ChangeClass(this)` is fine – Liam Dec 21 '16 at 16:24
  • In that case . function needs to accept a parameter and this still points to window object.to have the minimal changes we can do this approach – Geeky Dec 21 '16 at 16:38
2

In JavaScript this refers to the element containing the action. The way you use it in your function like that, you are not getting the DOM element clicked's scope, but only the function scope. The this you are referencing to in the onClick handler is not the DOM element you think it is. You need to Change your code to this:

<li ><a onclick="ChangeClass(this)" href="/Default.aspx">Home</a></li>

<script>
        function ChangeClass(element){
            element.className = "active";
        } 
</script>
callback
  • 3,981
  • 1
  • 31
  • 55