JQuery - apply content based class

I have a horizontal navigation menu where I can edit the source, my only option is to dynamically add classes when loading through JQUERY.

Imagine I have 3 tabs:

Home, Profile, Blog

Each with a link, for example:

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

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

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

+3
source share
3 answers
$("a").each(function () {
  var self = $(this);
  self.addClass(self.text());
});
+1
source

You can use :containsif you know what you are looking for:

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

I think this would be more reliable:

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

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

Assuming you give your navigation links a class nav.

+5

- :

$("a:contains('Home')").removeClass().addClass("Home");
+1

Source: https://habr.com/ru/post/1721067/


All Articles