Neha Thakur
Neha Thakur

Reputation: 351

In jquery how to get a matching element with a defined property(attribute) value

Below is my jQuery code, I want to get that li which has data-target="5". But my loop not enter in if condition even if there is a li with data-target="5".

var target = 5;
$("ul.menu-content li.collapsed").each(function() {
  if ($(this).is('[data-target]') == target) {
    $(this).removeClass('collapsed').find('a').addClass('active');
  }
});

Upvotes: 0

Views: 39

Answers (1)

Satpal
Satpal

Reputation: 133403

You need get data-target using .data(key) and compare its value.

if($(this).data('target') == target)

Or, You can directly use Attribute value selector and the code can be improved as

$("ul.menu-content li.collapsed[data-target=" + target+"]")
  .removeClass('collapsed')
  .find('a')
  .addClass('active');

Upvotes: 3

Related Questions