A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

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

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now