JQuery selection problem (all children inside a Div)

I am trying to attach a click function that adds a CSS class to all anchor tags inside a specific div. Somehow I can't get jQuery to do this (no JS error).

div:



<div id="better">
    <a href="1.aspx">One</a>
    <a href="2.aspx">Two</a>
    <a href="3.aspx">Three</a>
</div>

      

code>

My jQuery code (inside $ (document) .ready):



 $("#better > a").click(function() { $(this).addClass('active'); });

      

code>

I added an alert to my click function to see if it fires but nothing happens. As I wrote above, I also don't get JavaScript errors in the FF error console.

reference

Edit: This is just a sample code. Yes, it doesn't make sense to change the class when redirecting. I just simplified my code to the essence of what I am trying to do. :)

+2


source to share


5 answers


$("#better a").bind('click', function() { $(this).addClass('active'); });

      



+3


source


If I understand what you are asking, do you want to do this?

<div id="better">
    <a href="1.aspx" class="active">One</a>
    <a href="2.aspx" class="active">Two</a>
    <a href="3.aspx" class="active">Three</a>
</div>

      



If any link in that div was clicked, right? (you said all anchor marks) ... then use this:

$("#better").click(function() {
 $(this).find('a').addClass('active');
 return false;
});

      

+1


source


The warning works for me. However, why are you adding the class if you are redirected to a new page?

0


source


Two guesses:

  • Perhaps you have another element on your page from id="better"

    ? The id must be globally unique, so the selector will only return one of them.

  • Try to make the function click false false to prevent the user from clicking on the link. (It seems odd to add a class when the user leaves the page, if perhaps the link doesn't open in a new window.)

0


source


Try running the code at the bottom of the page, before the closing body tag or in the $ (document) .ready () function.

Using Firebug, you can use console.log () to log to the javascript console to make sure the selector is actually returning items. Example: console.log ($ ("# better> a"). Length)

0


source







All Articles