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 for the HTML data attributes.

Example

Other than that, you can try to run the following code to learn how to use jQuery selectors on custom data attributes using HTML5:

Live Demo

<!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
  var group = $('ol[data-group="Subjects"]');

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

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

});
</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>

Updated on: 18-Dec-2019

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements