How to use jQuery selectors on custom data attributes using HTML5?

To use jQuery selectors on custom data attributes, you can use contains, starts with, and ends with operators for the HTML5 data attributes. These selectors allow you to target elements based on their data-* attribute values using pattern matching.

jQuery Data Attribute Selector Operators

The main operators for selecting data attributes are ?

^= ? Selects elements whose attribute value starts with the specified string

*= ? Selects elements whose attribute value contains the specified substring

$= ? Selects elements whose attribute value ends with the specified string

Example

The following example demonstrates how to use jQuery selectors on custom data attributes using HTML5 ?

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            // Stored selector for the ordered list
            var group = $('ol[data-group="Subjects"]');

            // Selects elements whose data-subject starts with "M"
            var maths = $('[data-subject^="M"]', group).css('color', 'green');

            // Selects elements whose data-subject contains "graph"
            var graph = $('[data-subject*="graph"]', group).css('color', 'blue');

            // Selects elements whose data-subject ends with "ce"
            var science = $('[data-subject$="ce"]', group).css('color', 'red');
        });
    </script>
</head>
<body>
    <ol data-group="Subjects">
        <li data-subject="Maths">Maths</li>
        <li data-subject="Science">Science</li>
        <li data-subject="Geography">Geography</li>
        <li data-subject="History">History</li>
    </ol>
</body>
</html>

The output of the above code will display ?

Maths (in green color - starts with "M")
Science (in red color - ends with "ce") 
Geography (in blue color - contains "graph")
History (default color)

Conclusion

jQuery data attribute selectors provide powerful pattern matching capabilities for targeting HTML5 custom data attributes, making it easy to select and manipulate specific elements based on their data values.

Updated on: 2026-03-13T18:14:19+05:30

436 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements