user3130970
user3130970

Reputation: 49

Add a css class to an element if the element has a certain text via javascript

I need to add the class .active-trail to an li element if the li element has a link (a) as a child element containing the word "Help".

Example:

<li class="last expanded dropdown">

  <a href="/test1" title="" class="dropdown-toggle" data-target="#" data toggle="dropdown">
    Help <span class="caret"></span>
  </a>

</li>

<li class="last expanded dropdown">

  <a href="/test1" title="" class="dropdown-toggle" data-target="#" data toggle="dropdown">
    Contact <span class="caret"></span>
  </a>

</li>

In the example above, I would like to add the class active-trail to the first li like so:

<li class="last expanded dropdown active-trail">

  <a href="/test1" title="" class="dropdown-toggle" data-target="#" data toggle="dropdown">
    Help <span class="caret"></span>
  </a>

</li>

<li class="last expanded dropdown">

  <a href="/test1" title="" class="dropdown-toggle" data-target="#" data toggle="dropdown">
    Contact <span class="caret"></span>
  </a>

</li>

Is this possible through javascript/jQuery, and if so, how? Thanks!

Upvotes: 0

Views: 308

Answers (3)

Anid Monsur
Anid Monsur

Reputation: 4538

$.each($('li a'),function() {
    if ($(this).text.indexOf('Help') > -1) {
        $(this).parent().addClass('active-trail');
    }
});

Upvotes: 0

SpoonNZ
SpoonNZ

Reputation: 3829

$('li a').each(function() {
    if( $(this).text().toLowerCase().search('Help') >= 0 ) {
        $(this).closest('li').addClass('active-trail')
    }
})

Edit: I like Mohammad's solution better, but this should work too.

Upvotes: 0

Adil Shaikh
Adil Shaikh

Reputation: 44740

Like this -

$('a').filter(function(){
  return $(this).text().indexOf('Help') > -1;
}).closest('li').addClass('active-trail');

Upvotes: 2

Related Questions