0

When I convert multiple variables into multiple selectors the below code fails to execute.

DEMO HERE

$('.Btn').on('click', function () {
  var outer = $(this).data('test');
  var inner = $(outer).children('.Inner');
  $(outer + ',' + inner).addClass('Success');
});

In the code above:

This is successful

$(outer).addClass('Success');

This is successful

$(inner).addClass('Success');

This is not

$(outer + ',' + inner).addClass('Success');

QUESTION

How can multiple variables be used to create multiple jquery selectors?

1
  • That doesn't work because inner is not a string but an Object. Commented May 5, 2015 at 12:27

2 Answers 2

1

Your latter method will only work if both variables contain strings. In your case you need to use add() to join the objects held in the variables together:

$(outer).add(inner).addClass('Success');

Updated fiddle

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

Comments

1

In you script, outer is a string, but inner is a jQuery object. You can't connect these values to each other. Of course, you can get the inner class name as a string, but it's a bit tricky and not always work well...

If you must have the +','+ syntax, here's the solution, but as I mentioned, it's really hacky:

$('.Btn').on('click', function () {
    var outer = $(this).data('test');
    var inner = '.'+$(outer).children('.Inner').attr('class').split(' ')[0];
    $(outer+', '+inner).addClass('Success');
});

A better solution if you handle the inner div with something like add() or find().

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.