How to use javascript variables, JQuery selector?

These tutorials show multiple ways to use javascript variables in the Jquery selector.

Jquery selectors are used to selecting an element from a DOM tree using element, id, and class selectors.

Let’s declare div with id and class attribute

<div id="headingId" class="heading">Text example</div>

You can change the content inside using javascript

$("#headingId").innerHTML = "Div Example";

The above div is selected with the id string.

Can we pass a variable as selectors in JQuery?

Yes, It is possible

Jquery selector for a javascript variable

Let’s declare a text box in HTML.

<input type="text" id="fname" class="inputtext" />

Let’s see multiple ways to select textbox using a variable.

In this example, Change the text box value using the jquery selector with a variable. Declare a variable with an id string

Using ES6 template variable syntax.

template variable syntas is added in ES6. Variable declare and accessed with double-quotes using interpolation syntax.

let selector = "fname";
$("input[id=${selector}]").val("new value");

Another way using string concatenation

Append # to a variable selector using + operator as seen below

let selector = "fname";
$('input[id="' + selector + '"]').val("new value");

Another way using the id selector

let selector = "fname";
$('#"' + selector + '"').val("new value");

In the same way, we can use a class selector.

let selector = "inputtext";
$('".' + selector + '"').val("new value");

Conclusion

In a summary, It is possible to use javascript variables in jquery selectors to select the DOM element.