anderish
anderish

Reputation: 1759

Javascript to Change Class without use of ID Tag

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.

Upvotes: 1

Views: 1403

Answers (2)

callback
callback

Reputation: 4122

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>

Upvotes: 2

Geeky
Geeky

Reputation: 7496

'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

Upvotes: 5

Related Questions