Search code examples
jqueryjquery-selectorsconcatenation

Concatenated Jquery


I'm trying to grab a variable and distinguish which selector should be targeted. However when concatenating the string inside the selector the code no longer works.

This works:

$('#step2 .selection').eq(1).click(function() {
console.log(step); // Always returns 2
}

This doesn't:

$('#step'+ step +'.selection').eq(1).click(function() {
console.log(step);
}

Solution

  • $('#step'+ step +'.selection').eq(1).click(function() {
                      ^
    

    You're missing the space, so it's looking for a single element with both the ID and class. You need:

    $('#step'+ step +' .selection').eq(1).click(function() {
                      ^