Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Help needed with "Dynamic" addClass

  • This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #27701
    TerryWillard
    Member

    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?

    #69774
    Chris Coyier
    Keymaster
    Code:
    var text = ”;

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

    #69782
    noahgelman
    Participant
    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?

    #69786
    TerryWillard
    Member

    @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)
  • The forum ‘JavaScript’ is closed to new topics and replies.