Using string variables within a jquery selector

38 Views Asked by At

I have a variable which I define by:

  if($(this).hasClass('firstName')){
        lastname = $(this)
            current='.first-name'
        }

I have to use this variable in jQuery selector. I tried the following but it doesn't work:

$('.invitePartners' + current + '[data-index]')
2

There are 2 best solutions below

2
On

May be spaces between them as you may want descendant selector.

$('.invitePartners ' + current + ' [data-index]')

Else you will have a value like .invitePartners.first-name[data-index] which will look for an element with class invitePartners and first-name which also have an attribute data-index(something like <div class="invitePartners first-name" data-index="1"></div>)

0
On

They way you are trying to do will compile as: $('.invitePartners.first-name[data-index]');

I think, you need spaces between them to find heirarchical DOM elements:

$('.invitePartners ' + current + ' [data-index]');

[Space added after '.invitePartners' and before '[data-index]'], hopefully this will resolve your problem

OR

if($(this).hasClass('firstName')){
        lastname = $(this)
            current=' .first-name ';
        }

add space on both sides of current var value.