tags:

views:

49

answers:

3

I have a horizontal navigation menu which I can edit the source of, my only option is to add classes dynamically when it loads through JQUERY.

Imagine I have 3 tabs:

Home, Profile, Blog

Each with a link like so:

<a href="home.html">Home</a>

Is it possible for JQUERY to look between the <a> </a> tags and find the text (E.g. Home) and use that text as the class?

So my <a href="home.html"> becomes: <a class="Home" href="home.html">

+4  A: 

You can use :contains if you know what you're looking for:

$('a :contains(Home)').addClass('home');

I think this would be more robust:

$('a.nav').each(function() {

    // add class with name of the link's text
    $(this).addClass($(this).text());
});

Assuming you give your navigation links the class nav.

karim79
+1 Good solution
GenericTypeTea
+1 for second alternative.
chelmertz
+1  A: 

You want something like this:

$("a:contains('Home')").removeClass().addClass("Home");
GenericTypeTea
Karim79's 2nd example if probably more what you're after.
GenericTypeTea
A: 
$("a").each(function () {
  var self = $(this);
  self.addClass(self.text());
});
Tobias Baaz