Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery select class from variable

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

like image 842
Mr Hyde Avatar asked Oct 16 '10 23:10

Mr Hyde


People also ask

How do I select a class in jQuery?

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.

How do you select element by id in jQuery?

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.

Is jQuery a class?

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".


1 Answers

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.

like image 123
user113716 Avatar answered Sep 21 '22 14:09

user113716