开发者

document.getElementById not working for <a> tag

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 cli开发者_Go百科ck 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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜