WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
Advertisements

How to Find an Element Based on a Data-attribute Value in jQuery

Topic: JavaScript / jQueryPrev|Next

Answer: Use the CSS Attribute Selector

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>

Related FAQ

Here are some more FAQ related to this topic:

Advertisements
Bootstrap UI Design Templates

Your Feedback:

We would love to hear from you, please drop us a line.