AKS AKS - 4 days ago 6
jQuery Question

How to get concrete element by jquery selector?

I want to do something like:

if($(this).hasClass("playButton"))
{
$(this).find("li").removeClass("active");
}


But instead of "this" in "if" statement I want to use any class selector. But I don't know how to get concrete DOM element, which corresponds to the condition.
So I need:

if($(.anyClass).hasClass("playButton"))
{
$(current element, which corresponds to
if condition).find("li").removeClass("active");
}

Answer

You can select the elements using the ".anyClass" selector and then iterate through them using each. In the callback function of each, this will refer to the current DOM element.

$(".anyClass").each(function() {
  if ($(this).hasClass("playButton")) {
    $(this).find(".btn").removeClass("playButton");            
  }
});

However, for this particular scenario, you can reach your goal without using each. Simply target the element directly and manipulate it, as @Derek朕會功夫 suggested in his answer.

$(".playButton li").removeClass("active");
Comments