views:

194

answers:

2

hi,

I'm very new to js so kindly help me with this.

I am trying to add a class to a tag using onClick.

The code is as shown below:

<a class="gkvSprite" href="#" id="abc" onClick="showhide('1')">Click 1</a>
<a class="gkvSprite" href="#" id="def" onClick="showhide('2')">Click 2</a>
<a class="gkvSprite" href="#" id="hij" onClick="showhide('3')">Click 3</a>

Now when i click i need to add a class called "selected" for the one i select. I tried using setAttribute and add class of jquery as well but was not successful

When i alert the document.getelementbyId(123) it gives out the link.

Can someone kindly help me?

Thanks in Advance
Alloi

+7  A: 

id should begin with an alphabet.

Official specification

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").


Also,

var element = document.getElementById('id');
element.className += "newClass";

The showhide() should do something like above.

N 1.1
i changed that to alphabets but, its still the same result
Alloi
It worked now. Thanks a lot! :)
Alloi
+1  A: 

Without seeing the code for showhide there is no way to see exactly what you're doing wrong. Since you mention jQuery, here is how to do what you describe with it:

$('.gkvSprite').click(function() {
  $(this).addClass('selected');
});

It's also worth noting that it's invalid to start an ID with a number.

Jimmy Cuadra
document.getElementById('abc').setattribute("className", "some_class_name"); I am executing the above code.When i alert document.getElementById('abc') it shows http://localhost/gkv/# and not as an object.
Alloi
Thanks a lot :)
Alloi
The function is `setAttribute` and it's case sensitive. With that change, your code works for me. Also note that when you use `alert`, you are shown the "value" of the link element. If you use `console.log` instead, which you should always be doing for debugging, you'll see that it's actually the entire DOM element.
Jimmy Cuadra