1

I have a very simple Javascript (jQuery) code, which just add a class name to the HTML link <a> element when the link is clicked, then use CSS to change the link background to red.

You will see in my code, I defined the background color for HTML link visited, hover, active . The Javascript (jQuery) code is just to addClass() to the <a> link tag to change the background color to red by using CSS if the link has been clicked.

My code is here on jsfiddle, Why it does not work?

---------------New problem------------------------

Seems the thing get different if I put the link inside a table (as a content of <td>), like this code shows, why now the background does not change to red???? (But the font size did change, strange, seems partly highlighted)

4 Answers 4

2

First, jQuery objects have .addClass available. So not this.addClass, but $(this).addClass. $(this) creates a jQuery object from an element.

Secondly, a .highlight means: any descendants of <a> elements with a class of highlight. You want <a> elements which have that class themselves, so use a.highlight (without the space).

http://jsfiddle.net/YJH9g/10/

3
  • Ah, yup, I was about to give the same answer. But you explained it better than I would have. +1
    – Yoshiyahu
    Oct 16, 2011 at 21:01
  • Could you also help on the similar case here, the only difference is I put the link to a table <td>, it does not show the highlight background still, Here is the code: jsfiddle.net/YJH9g/27
    – Leem.fin
    Oct 16, 2011 at 21:10
  • @Leem.fin: You should never use an ID twice in one document - then you destroy the idea of an ID (it should be unique). Also, adding !important in CSS makes a rule superior to others. I used a class name instead of an ID: jsfiddle.net/YJH9g/29.
    – pimvdb
    Oct 16, 2011 at 21:13
1

addClass is a jQuery function; this is a native DOM element.

You need $(this)

1

you need to use $(this)

$("#my-link").click(function(){
    $(this).addClass("highlight");
});
1
  • Could you also help on the similar case here, the only difference is I put the link to a table <td>, it does not show the highlight background still, Here is the code: jsfiddle.net/YJH9g/27
    – Leem.fin
    Oct 16, 2011 at 21:13
0

For your second question: You can not use an id multiple times! What you can do is use classes:

<table border="1">
<tr>
   <td class="col">
       <a class="my-link" href="#">Home</a>
    </td>
    <td class="col">
       <a class="my-link" href="#">Help</a>
    </td>
</tr>
</table>

js

$(".my-link").click(function(){
    $(this).addClass('highlight');
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.