max_
max_

Reputation: 24481

addClass() is not adding the class

I am using jQuery for the first time to add a class to an element within the navigation bar, but the class, '.selected' isn't being added.

Please can you tell me where I am going wrong?

Here is an example: http://jsfiddle.net/v32qy/2/

Thanks!

Upvotes: 0

Views: 89

Answers (3)

Virendra
Virendra

Reputation: 2553

To access the current element you have to use $(this) and not just this

Here is the updated fiddle. http://jsfiddle.net/v32qy/6/

I have also changed the way you are getting the inner text to use jQuery text() function

Upvotes: 0

Ry-
Ry-

Reputation: 224845

this is not a jQuery object, it's the actual DOM element. To turn it into a jQuery object, use $(this). So:

$(this).addClass('selected');

Another problem in the jsFiddle is that you're not selecting the <a> element, you're selecting the <h2>. Finally, the link is being followed. Here's all that fixed.


Something else you might consider is that element.innerText doesn't have very good browser support from what I've seen (i.e. it only works in IE). Just a small point of note.

Upvotes: 7

Scott
Scott

Reputation: 21882

You want apply the class to the anchor, in addition to correcting the syntax.

$('#textContainer h2 a').click(function() {
    var title = this.innerText;
    $(this).addClass('selected');
 });

Upvotes: 0

Related Questions