1

I'm having a difficult time getting a selector to work properly. I have a class name stored in a variable, which I would usually select like:

$("." + class_name)

When I do this, however, I'm getting the error: Syntax error, unrecognized expression: . as if it's not recognizing the class selector.

Almost every other example of how to select classes based on variables uses this method as well, am I missing something really basic here? Thanks for your help.

5
  • 2
    what is the value of class_name Commented Jan 9, 2014 at 16:46
  • "group2" I can run console.log( $(".group2").length ); and get the proper result. Commented Jan 9, 2014 at 16:47
  • 1
    can you post some more code? Commented Jan 9, 2014 at 16:49
  • can you log console.log("." + class_name) before the selector Commented Jan 9, 2014 at 16:49
  • 2
    from what I can see class_name has a empty string value Commented Jan 9, 2014 at 16:51

4 Answers 4

1

First, do an alert(class_name) on the line immediately before this to make sure class_name actually has a value. Also, make sure the class name is spelled properly in both the variable and in your style sheet. Also, remember, css classes are CASE-SENSITIVE, so "myClass" <> "Myclass". If all that checks out, try creating a variable on the line before the alert and assigning "." + class_name to it. Something like this:

var fixit = "." + class_name;
$(fixit);

Let me know if none of this helps.

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

1 Comment

Thats what it was. The class names are being fed by an array, which somehow gets an empty string as the first one. It seems like this was the first correct answer so I will accept it in a few minutes when it lets me. Thanks everyone.
1

You probably have a '.' in class_name as well, so you're trying to select $('..class_name'). Do console.log(class_name) to confirm. Either that, or class_name is undefined

Comments

0

You can try something like

 var class_name = "container";
 var selector = "."+class_name;

 $(selector).html("hello universe !");
 console.log(typeof (selector)); //prints "string"

FIDDLE

Comments

0

I think class name is not in double quotes or empty.Following code is working fine in jsFiddle

var className="test"
alert($("." + className).html());

JSFIDDLE

Comments

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.