• jQuery Video Tutorials

jQuery [attribute~=value] Selector



The [attribute~=value] in jQuery is used to selects elements with an attribute containing a specified value within a space-separated list.

In other words, It selects elements where the specified attribute's value is exactly the given value or contains the given value within a space-separated list.

Syntax

Following is the syntax of [attribute~=value] Selector in jQuery −

$("[attribute~='value']")

Parameters

Here is the description of the above syntax −

  • attribute: The attribute whose value will be checked.
  • value: The word that should be contained within the attribute's value. The value must be a whole word, not a part of a word.

Example 1

In the following example, we are using the jQuery [attribute~=value] Selector to select all elements with the class "highlight" in the class attribute −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("[class~=highlight]").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <div class="highlight">This div will be highlighted.</div>
    <div class="nohighlight">This div will not be highlighted.</div>
    <div class="highlight another-class">This div will also be highlighted.</div>
</body>
</html>

After executing the above program, the selected elements will be highlighted with yellow background color.

Example 2

In this example, we are selecting elements with a data attribute containing "feature" −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("[data-tags~=feature]").css("border", "2px solid red");
        });
    </script>
</head>
<body>
    <div data-tags="feature new">This div has the 'feature' tag.</div>
    <div data-tags="old popular">This div does not have the 'feature' tag.</div>
    <div data-tags="feature popular">This div also has the 'feature' tag.</div>
</body>
</html>

After executing the above program, a solid red border will be applied to the selected elements.

jquery_ref_selectors.htm
Advertisements