1

I m using jQuery for my drupal site. I can't add class to current element by using jQuery.

I put this addclass inside a if condition with alert. Alert has working fine. But addclass not working.

if (jQuery(".explore_degree_widget_area li a").has(":contains('Associates')")) { 
    jQuery(this).addClass('icon_associate');
    alert('Yes');
}

Can you help me?

2
  • 2
    You can only get $(this), if you are using it inside any event. Commented Jun 16, 2016 at 10:35
  • @DharaParmar Wrong. You can use $(this) inside .each() iteration and callback functions in methods like .text(), .html() etc. Commented Jun 16, 2016 at 10:40

3 Answers 3

3

If condition would be always true, since has() returns filtered jQuery object. Also has() avoid text nodes, it's only check on it's descendant, You need to use filter() .

jQuery(".explore_degree_widget_area li a").filter(":contains('Associates')").addClass('icon_associate');

or use combined selector

jQuery(".explore_degree_widget_area li a:contains('Associates')").addClass('icon_associate');
Sign up to request clarification or add additional context in comments.

2 Comments

There is no need in .has(): combine it in the selector.
@BhavanKumarNatarajan : glad to help :) you need to use filter() not has()
1

this refers to the context but not to the element. Use the following:

jQuery(".explore_degree_widget_area li a:contains('Associates')")
    .addClass('icon_associate').each(function() {
        alert('Yes');  // if you really want to have it
    });

Comments

0

Try

$(".explore_degree_widget_area li a:has(:contains('Associates'))").addClass('icon_associate');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.