admin管理员组

文章数量:1414614

I want to add a class to a li with specific Id. I tried this:

function updateIndex(indexValue){
    $('li[id=' + indexValue + ']').addClass("selectedQuestion")

}

I am not able to access indexValue variable in the li selector.

I want to add a class to a li with specific Id. I tried this:

function updateIndex(indexValue){
    $('li[id=' + indexValue + ']').addClass("selectedQuestion")

}

I am not able to access indexValue variable in the li selector.

Share Improve this question edited Jun 23, 2015 at 12:16 Vivek Sadh asked Jun 23, 2015 at 12:10 Vivek SadhVivek Sadh 4,2683 gold badges35 silver badges54 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

You need to do a string concatenation to use the value of the indexValue parameter:

$('li[id=' + indexValue + ']').addClass("selectedQuestion")

Or, given the attribute you are selecting by is an id:

$('li#' + indexValue).addClass("selectedQuestion");

Or, given that id is supposed to be unique you shouldn't need the 'li' part (unless your meaning is to select that element only if it has that id and is an li element):

$('#' + indexValue).addClass("selectedQuestion");
function updateIndex(index){
   $('li[id=' + index +']').addClass("selectedQuestion")

}

Use this code instead of yours. You have to concatinate the indexValue variable

function updateIndex(indexValue){
  $('li[id=' + indexValue + ']').addClass("selectedQuestion")

}

本文标签: javascriptAdd class to li with specific IDStack Overflow