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
In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
jQuery hasClass() MethodThe hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With