In this article, we'll learn how to locate elements using data-attribute values. We can do this using jQuery and CSS attribute selectors. These selectors help us pick out HTML elements based on the values in their data attributes.
In simple terms, we're going to explore how to use jQuery to find elements based on their data attributes. This knowledge will come in handy for various web development tasks, so let's dive into how to achieve it.
Example: How To Get Element By Data Attribute In jQuery
<!DOCTYPE html>
<html lang="en">
<head>
<title>How To Get Element By Data Attribute In jQuery - Websolutionstuff</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(){
var slide = $(this).children("option:selected").val();
$(".slides img").removeClass("selected");
$('.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/laravel.jpg" alt="Laravel" data-slide="1">
</li>
<li>
<img src="images/jquery.jpg" alt="jQuery" data-slide="2">
</li>
<li>
<img src="images/php.jpg" alt="PHP" data-slide="3">
</li>
<li>
<img src="images/html.jpg" alt="HTML" data-slide="4">
</li>
</ul>
</body>
</html>
In conclusion, we've gained the valuable skill of finding and manipulating elements in our web development projects based on their data attributes. With the power of jQuery and CSS attribute selectors, we can easily locate and work with specific elements that have the data attributes we need.
You might also like:
In this article, we will see how to merge two collections in laravel 8 or laravel 9. The Illuminate\Support\Co...
Jul-18-2022
In this article, we will delve into the process of disabling sorting for specific columns in Datatables. If you find the...
Aug-24-2020
Checkboxes let us make multiple choices. But how do you actually use them in JavaScript? It might seem tricky, especiall...
Jan-10-2023
In this example we will see Laravel Eloquent relationships, laravel provides many relationship like laravel ha...
Mar-23-2021