0

I am trying to add a class to a div that has a class with a variable name. This is the code I am using:

if ($('div').hasClass(this.filterSelection)) {
        $(this).addClass('highlightMenu');
}

The 'this' isn't doing what I want it to, but I don't know what to put in its place. Any ideas will be much appreciated.

2
  • What exactly do you want it to do? ..*` a div that has a class with a variable name.`* that's confusing. Commented Oct 9, 2017 at 22:44
  • I want to highlight the div that's being filtered on. That's why I added the name of the element being filtered as a class; that way, I can target that specific div. Commented Oct 9, 2017 at 23:11

1 Answer 1

1

$(this) is referring to the entire document. This is because $('div').hasClass(this.filterSelection) does not have any chained functions on it. So the line $(this).addClass('highlightMenu'); does not get the $(this) value.

try this.

this.filterSelection = 'someFilter'; // I am just hard coding the filterSelection here
var classCheck = this.filterSelection; // store the filterSelection in a variable

$(document).ready(function(){
  var $div = $('div');

  $div.each(function(){
    if ($(this).hasClass(classCheck)) {
      $(this).addClass('highlightMenu');
    }
  });
});

<div class="someFilter"></div>
Sign up to request clarification or add additional context in comments.

5 Comments

Oh I see your point now. So your page has a bunch of div elements. and you want to add the highlight class to the div which has a specific class or attribute. is this correct ?
Exactly. To that specific div.
@DwightMendoza Observe the $(this) inside the $div.each callback. The callback is fired in the context of the current DOM element, so the keyword this refers to the element. api.jquery.com/each
That worked! I just had to move the 'classCheck' variable assignment outside and prior to the (document).ready function. Otherwise, the value of this.filteredSelection was not being carried in to the function. Please update your answer to reflect this and I'll check it off. Thanks much!

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.