You can use the CSS attribute selectors to find an HTML element based on its data-attribute value using jQuery. The attribute selectors provide a very powerful way to select elements.
Let's check out the following example to understand how it works:
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Selecting Element by Data Attribute</title>
<style>
ul li {
float: left;
margin: 10px;
list-style: none;
}
ul li img.selected{
outline: 5px solid black;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("select").change(function(){
// Get selected option value from dropdown
var slide = $(this).children("option:selected").val();
// Remove existing selected class from the image
$(".slides img").removeClass("selected");
// Select image based on its data-slide attribute value
$('.slides img[data-slide=' + slide + ']').addClass("selected");
});
});
</script>
</head>
<body>
<label>Slide:</label>
<select>
<option>select</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
<hr>
<ul class="slides">
<li>
<img src="images/club.jpg" alt="Club" data-slide="1">
</li>
<li>
<img src="images/diamond.jpg" alt="Diamond" data-slide="2">
</li>
<li>
<img src="images/spade.jpg" alt="Spade" data-slide="3">
</li>
<li>
<img src="images/heart.jpg" alt="Heart" data-slide="4">
</li>
</ul>
</body>
</html>
Use the CSS
Attribute
SelectorYou can use the CSS attribute selectors to find an HTML element based on its data-attribute value using jQuery. The attribute selectors provide a very powerful way to select elements.
Let's check out the following example to understand how it works:
need an explanation for this answer? contact us directly to get an explanation for this answer