Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - Apply class based on contents of <a>

Tags:

jquery

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">

like image 919
CLiown Avatar asked Nov 18 '25 19:11

CLiown


2 Answers

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.

like image 113
karim79 Avatar answered Nov 20 '25 08:11

karim79


$("a").each(function () {
  var self = $(this);
  self.addClass(self.text());
});
like image 37
Tobias Baaz Avatar answered Nov 20 '25 07:11

Tobias Baaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!