Forums

  • # January 21, 2010 at 8:28 pm

    I need to add different classes to different anchor elements. The code is dynamically generated so hard coding is out. I’m a complete learner with jQuery though I understand the basics.

    Code:

    Above is a simplified version of the dynamically output code. I need to get the text from between the anchor then add it as a class to the same anchor it was pulled from. So the output will be:

    Code:

    The closest I’ve got with jQuery is this:

    Code:
    $(“ul.colors”).each(function(){
    var Text = $(“ul.colors a “, this) .text();
    $(“ul.colors a”, this) .addClass(“”+ Text +””);
    });

    But I seem to end up with BlueWhiteGreen as the class for each of the anchors. Any help?

    # January 21, 2010 at 9:59 pm
    Code:
    var text = ”;

    $(“ul.colors li a”).each(function(){
    $(this).addClass($(this).text());
    });

    # January 22, 2010 at 4:00 am
    Code:
    $(document).ready(function() {
    $(‘ul.colors a[href*=/color/blue/]’).addClass(‘blue’);
    $(‘ul.colors a[href*=/color/white/]’).addClass(‘white’);
    $(‘ul.colors a[href*=/color/green/]’).addClass(‘green’);
    });

    This also good?

    # January 22, 2010 at 9:35 am

    @robskiwarrior Yes that is exactly what I want. The value of the anchor is pulled from a database that could have new ‘colors’, in this example, added. So doing it like @noahgelman would requird me to always be updating my jQuery. My original way would get all the values of all the anchors in the ul, resulting in all anchors being given a the same class of BlueWhiteGreen. Of course this would be useless as I need the class to pull in some CSS.

    I have yet to test the solution by @chriscoyier but it looks like it should do the trick. I’ll be back later to share. Thank you all.

    UPDATE: I’ve just implemented the solution from @chriscoyier and it works as intended. Thank you.

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.

icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag