- This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
Viewing 4 posts - 1 through 4 (of 4 total)
- The forum ‘JavaScript’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › Help needed with "Dynamic" addClass
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.
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:
The closest I’ve got with jQuery is this:
But I seem to end up with BlueWhiteGreen as the class for each of the anchors. Any help?
$(“ul.colors li a”).each(function(){
$(this).addClass($(this).text());
});
This also good?
@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.