0

I'm creating a web application, where I got a simple problem which I can't solve. I've put the code which creates the problem here: http://jsfiddle.net/rkumarnirmal/5w3FG/

What's problem with the second alert() which should display this answer

current

The problem is:

var b = '.something';
var c = $(b).attr("id");
alert(c);

is not showing the id.

But, When I give

var c = $('.something').attr("id");
alert(c);

It works. Have I done anything wrong with the selector?

Thanks!

0

3 Answers 3

3

Your fiddle is actually different.

var b = "." + a.split(/\s+/).pop();

works because it's a . followed by a class name. You included both " and ' in the string which means ' is part of the selector (which is a syntax error).

You can pass a string like $("abc") in which abc is the selector. If you use a variable like this:

var selector = "abc";  // the selector abc stored in a variable as a string
$(selector);           // the selector is passed to jQuery

then you shouldn't use additional 's or "s.

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

Comments

1
$(function(){
var a = $('#current').attr("class");
var b = "."+a.split(/\s+/).pop(); // not "'."+a.split(/\s+/).pop()+"'";
    alert(b);
var c = $(b).attr("id");
    alert(c);
});

DEMO

Comments

0
var a = $('#current').attr("class");
var b = "." + a.split(/\s+/).pop();
alert(b);
var c = $(b).attr("id");

alert(c);

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.