How To Get Element By Data Attribute In jQuery

    In this article, we will see how to find elements based on data-attribute value. You can use the CSS attribute selectors to find an HTML element based on its data-attribute value using jQuery. The selector is used to select elements with a specified attribute. We can use the CSS Attribute selector to get the element.

    So, let's see jquery find data attribute value, and jquery get element by attribute.

    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>

    You might also like:

Bình luận
Vui lòng đăng nhập để bình luận
Một số bài viết liên quan