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 select 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 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 text box value using 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 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");


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

Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.