• jQuery Video Tutorials

jQuery [attribute|=value] Selector



The [attribute|=value] Selector in jQuery is used to select elements that have the specified attribute with a value either equal to value or starting with value- followed by a hyphen.

Syntax

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

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

Parameters

Here is the description of the above syntax −

  • "attribute": Specifies the attribute you want to select.
  • "|=": Represents the operator indicating the value should be equal to value or start with value.
  • "value": The value or prefix to match against the attribute.

Example 1

In the example below, we are selecting all <div> elements with a lang attribute starting with "en" using the jQuery [attribute|=value] Selector −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            var elements = $("[lang|=en]");
            elements.css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <div lang="en">English Content</div>
    <div lang="en-us">American English Content</div>
    <div lang="fr">French Content</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 all <p> elements with a title attribute starting with "Hello" −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            // Select all elements with a title attribute starting with 'Hello'
            $("p[title|='Hello']").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <p title="Hello">Greetings!</p>
    <p title="hello">Welcome!</p>
    <p title="Hello World">Farewell!</p>
</body>
</html>

When we execute the above program, the selected elements will be highlighted with yellow background color.

jquery_ref_selectors.htm
Advertisements