0

How can I use a variable inside jquery id selector?

function more_comments(x){
    var datalist = "#s" + x;

    $('datalist li:hidden').slice(0, 2).show();
}

I've tried this

var datalist = "s" + x;
$('#datalist li:hidden').slice(0, 2).show();

and this.

$('#s' + x li:hidden').slice(0, 2).show();

If i manually write

$('#s50 li:hidden').slice(0, 2).show();

and click on the tag with an id == s50, it works perfectly. I searched for the correct syntax and can't find it. Thanks for any help.

1
  • $(`#s${x} li:hidden`) Commented Jul 15, 2017 at 17:29

2 Answers 2

1

Have you tried like this?

var x = 's50';
$('#' + x + ' li:hidden').slice(0, 2).show();
Sign up to request clarification or add additional context in comments.

3 Comments

@baao sorry my bad :) thnx
Works perfectly. Thanks!
@John glad it works for you, by the way you can accept my answer :)
0

If you want to concatenate a variable and a string, the variable needs to be outside of any ' or ":

function more_comments(x){
    var datalist = "#s" + x;
    $(datalist + ' li:hidden').slice(0, 2).show();
}

Using a template string (not supported by IE), you could use

$(`#s${x} li:hidden`).slice(0, 2).show();

And to avoid the variable creation beforehand

function more_comments(x){
    $('#s' + x + ' li:hidden').slice(0, 2).show();
}

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.