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
Selected Reading
How to concatenate variable in a string in jQuery?
You can easily concatenate variables in a string in jQuery using the jQuery html() method. This technique allows you to dynamically insert variable values into HTML strings, making your web pages more interactive and dynamic.
String Concatenation Methods
There are several ways to concatenate variables in strings with jQuery ?
- Using the + operator ? The most common method for string concatenation
- Template literals ? Modern ES6 approach using backticks
-
jQuery methods ? Using
.html(),.text(), or.append()
Example
Try to run the following code to learn how to use variables in a string with jQuery ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
$("a").click(function(){
var id = $(".id").html();
var message = "Welcome to our website!";
$('.demo').html("<br><div class='new' id='" + id + "'>" + message + "</div>");
});
});
</script>
</head>
<body>
<div class="wrap">
<a href="#">Click me</a>
<div class="demo"></div>
<div class="id">Qries</div>
</div>
</body>
</html>
The output of the above code is ?
When you click the "Click me" link, a new div element will be created with: - ID attribute set to "Qries" (from the variable) - Text content "Welcome to our website!" - The new element will appear below the link
Alternative Method Using Template Literals
You can also use ES6 template literals for cleaner syntax ?
$(function(){
$("a").click(function(){
var id = $(".id").html();
var message = "Welcome to our website!";
$('.demo').html(`<br><div class='new' id='${id}'>${message}</div>`);
});
});
Conclusion
Concatenating variables in jQuery strings is essential for creating dynamic content. Use the + operator for traditional concatenation or template literals for modern, readable syntax.
Advertisements
