use javascript variable in jquery selector

How to Use JavaScript Variables in jQuery Selectors

jQuery provides a wide range of selectors to help you precisely select elements even from the most complicated DOM structures, in a simple way. Typically, developers use literal strings to create jQuery selectors. But sometimes you may need to use JavaScript Variables in jQuery selectors. In this article, we will learn how to do this.

How to Use JavaScript Variables in jQuery Selectors

Let us say you have the following element.

<div id='myDiv' class='myClass' name='myName' data='myData'>...</div>

Typically, we select div using its ID attribute as shown below.

$('#myDiv')
or
$('.myClass')

If you want to select the element using JavaScript variable, then you can define the text within quotes above directly as use it as shown.

var id='#myDiv';
var class='.myClass';

$(id)
OR
$(class)

Or you can define the ID or classname and concatenate it with # or dot(.) operator.

var id='myDiv';
var class='myClass';

$('#'+id)
OR
$('.'+class)

You can also use this approach to select multiple elements using multiple variables, as shown below. Please note, in this case, we will be use comma to separate individual selectors.

var id1='myDiv1';
var id2='myDiv2';
var class1='myClass1';
var class2='myClass2';

$('#'+id1+',#'+id2) //#myDiv1,#myDiv2
OR
$('.'+class1+',.'+class2) //#myClass1,#myClass2

Similarly, you can also define JS variables for name and use it in jQuery selector as shown below.

var name='myName';
$('div[name='+name+']')

You can also use the same approach for defining variables for other HTML attributes and properties and use them in jQuery selector.

var data='myData';
$('div[data='+data+']')

In this article, we have seen several ways to use JavaScript variables in jQuery selector. The key is to quote the literal parts correctly and use the concatenation operator ‘+’ at the right places. In most cases, jQuery gives error because the final concatenated string is malformed. If you take care of these two things, you should be able to select one or more elements using JS variables.

Also read:

How to Select Element With Multiple Classes
How to Show Last Queries in PostgreSQL
How to Generate Random Color in JavaScript
How to Read from Stdin In Python
How to Download Large Files in Python

Leave a Reply

Your email address will not be published. Required fields are marked *