Neha Thakur Neha Thakur - 22 days ago 10
jQuery Question

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');
}
});



Answer

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');
Comments