• jQuery Video Tutorials

jQuery [attribute^=value] Selector



The [attribute^=value] selector in jQuery is used to select elements whose attribute starts with a specific value. In other words, It allows you to target elements based on the beginning portion of their attribute values.

Syntax

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

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

Parameters

Here is the description of the above syntax −

  • attribute: Specifies the attribute you want to match.
  • value: The value that the attribute's value should start with.

Example 1

In the following example, we are using the jQuery [attribute^=value] Selector to select elements with "href attribute" starting with "https://" −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("a[href^='https://']").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <a href="https://example.com">Secure Example</a><br>
    <a href="http://example.com">Non-Secure Example</a><br>
    <a href="https://openai.com">OpenAI</a><br>
    <a href="https://google.com">Google</a>
</body>
</html>

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

Example 2

Here, we are selecting all image elements whose src attribute starts with "https://

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("img[src^='https://']").css("border", "2px solid green");
        });
    </script>
</head>
<body>
    <img src="https://example.com/image1.jpg" alt="Image 1"><br>
    <img src="http://example.com/image2.jpg" alt="Image 2"><br>
    <img src="https://openai.com/logo.png" alt="Logo"><br>
    <img src="https://google.com/banner.jpg" alt="Banner">
</body>
</html>

After executing the above program, the selected image elements will be highlighted with solid green color.

jquery_ref_selectors.htm
Advertisements