Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to use a variable in a string in jQuery?
jQuery is a JavaScript library introduced to make development with JavaScript easier. Let us see how to use a variable in a string using jQuery methods like html() and template literals.
Using String Concatenation
The most common way to use variables in strings is through string concatenation using the + operator. This allows you to combine static text with dynamic variable values.
Example
You can try to run the following code to learn how to use variable in a string in jQuery ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(function(){
$("a").click(function(){
var id = $(".id").html();
$('.myclass').html("<br><div class='new' id='" + id + "'>Hello</div>");
});
});
</script>
</head>
<body>
<div class="wrap">
<a href="#">Click me</a>
<div class="myclass"></div>
<div class="id">Learners</div>
</div>
</body>
</html>
The output of the above code is ?
When you click the "Click me" link, it will create a new div element with id="Learners" containing the text "Hello".
Using Template Literals
Modern JavaScript also supports template literals using backticks (``) and ${} syntax for cleaner variable interpolation ?
$(function(){
$("a").click(function(){
var id = $(".id").html();
$('.myclass').html(`<br><div class='new' id='${id}'>Hello</div>`);
});
});
Conclusion
Using variables in strings with jQuery can be accomplished through string concatenation or template literals, making it easy to create dynamic HTML content based on user interactions or data values.
