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 pass a variable into a jQuery attribute-contains selector?
Yes, it is possible to pass a variable into a jQuery attribute-contains selector. The [attribute*=value] selector is used to select each element with a specific attribute and a value containing a string. This technique is particularly useful when you need to dynamically search for elements based on variable content.
Syntax
To pass a variable into a jQuery attribute-contains selector, use string concatenation ?
$('[attribute*="' + variableName + '"]')
Example
You can try to run the following code to learn how to pass a variable into a jQuery attribute-contains selector ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(function() {
var testString = "vp-485858383";
$('div[data-vp*="' + testString + '"]').css('color', 'blue');
});
</script>
</head>
<body>
<div data-vp='{
id: vp-485858383,
customTwo: "test"
}'>
Hello World
</div>
<div data-vp='{
id: vp-123456789,
customTwo: "other"
}'>
Another Element
</div>
</body>
</html>
The output of the above code is ?
Hello World (displayed in blue color) Another Element (displayed in default color)
In this example, the variable testString contains the value "vp-485858383". The selector searches for any div element whose data-vp attribute contains this string, and applies blue color styling to the matching element.
Conclusion
Passing variables into jQuery attribute-contains selectors enables dynamic element selection based on runtime values. This approach is essential for creating flexible and interactive web applications.
