0

How do I use a variable to replace the value of the id selector string in jQuery?

For example, I can return the correct answer using the actual string "1325":

var textAddForm = jQuery(".ms-itmHoverEnabled[id*='1325']").find( "div" ).attr
("title");

but how would I use a variable value to replace the function of '1325' using jquery?

This doesn't work of course:

var val = 1325;
var textAddForm = jQuery(".ms-itmHoverEnabled[id*=val]").find( "div" ).attr("title");

1 Answer 1

1

There are many ways to do this. All you have to do is edit the string parameter you pass to your jQuery() function, making sure your val variable gets in there somehow.

Some examples are:

var val = 1325;
var textAddForm = jQuery(".ms-itmHoverEnabled[id*=" + val + "]").find( "div" ).attr("title");

or (using the ` character instead of quotes):

var val = 1325;
var textAddForm = jQuery(`.ms-itmHoverEnabled[id*=${val}]`).find( "div" ).attr("title");

or (prepare the selector string before using it):

var val = 1325;
var selector = ".ms-itmHoverEnabled[id*=" + val + "]";
var textAddForm = jQuery(selector).find( "div" ).attr("title");
Sign up to request clarification or add additional context in comments.

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.