12

I am using Jquery to find a class by variable. So,

var className = "whatever";

$("#container ul li") if contains element with className, do this

How do I write the above code?

Is it

$("#container ul li").find("."+ className).each(function(){
console.log("I found one");
});

Obviously the code doesn't work

1 Answer 1

26

Is the className on the <li> element? If so, you could do this:

$('#container ul li.' + className)...

You're just concatenating the className into the selector string (with the class selector).

Or this will give you the same result.

$('#container ul li').filter('.' + className)...

Which is the similar to your .find() solution, but uses .filter() to limit the <li> elements found to those with the className.


If the element with the className is a descendant of the <li> element, then using .find() should work, or you could do:

$('#container ul li .' + className)...

...which almost looks the same as the one above, but introduces a space after li, which is a descendant selector.

Sign up to request clarification or add additional context in comments.

1 Comment

The filter solution works. Thanks for clarifying that find() is used to find descendants!

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.