How to Use jQuery Selectors on Custom Data Attributes

jQuery provides several selectors to make the queries you are looking for. The starts with, ends with, and contains() selectors also can be used to select the specified string.

Let’s consider the HTML list:

<ul data-group="Books">
  <li data-book="JavaScript"></li>
  <li data-book="CSS"></li>
  <li data-book ="HTML"></li>
</ul>

Using the basic querying to get all elements with data-book="JavaScript" below "Books" and to get all elements with data-book!="JavaScript" below "Books" you should use the following:

$("ul[data-group='Books'] li[data-book='JavaScript']")
$("ul[data-group='Books'] li:not([data-book='JavaScript'])")

You can also use several meta selectors. If you want to do multiple queries, it is recommended to cache the parent selection:

let group = $('ul[data-group="Books"]');

Then you can look for books that start with C:

let css = $('[data-book^="C"]', group).css('color', '#qc87c9');

Or the books that contain the word script:

let javascript = $('[data-book*="Script"]', group).css('color', '#8ebf42');

You can also get elements whose data attribute's ending matches:

let html = $('[data-book$="ML"]', group).css('color', '#ff0000');

Here the full example. try and see how it works:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
  </head>
  <body>
    <ul data-group="Books">
      <li data-book="JavaScript">JavaScript</li>
      <li data-book="CSS">CSS</li>
      <li data-book="HTML">HTML</li>
    </ul>
    <script>
      $(document).ready(function() {
          //stored selector
          let group = $('ul[data-group="Books"]');
          //data-book starts with C
          let css = $('[data-book^="C"]', group).css('color', '#qc87c9');
          //data-book contains script
          let javascript = $('[data-book*="Script"]', group).css('color', '#8ebf42');
          //data-book ends with ML
          let html = $('[data-book$="ML"]', group).css('color', '#ff0000');
        });
    </script>
  </body>
</html>

jQuery Selectors

jQuery provides a set of tools for matching a set of elements in a document which is formed from borrowing CSS 1-3. The :contain() selects all elements containing the given string. The starts with selector selects elements that have the given attribute with a value beginning exactly with a specified string. The ends with selector selects elements that have the given attribute with a value ending exactly with a specified string.

Do you find this helpful?

Related articles