• jQuery Video Tutorials

jQuery [attribute] Selector



The jQuery [attribute] selector in jQuery is used to select elements that have a specified attribute.

You can also select elements where the attribute has a specific value, elements where the attribute contains a certain value, and more using other selectors in jQuery.

Syntax

Following is the syntax of [attribute] selector in jQuery −

$("[attribute]")

Parameters

The "[attribute]" selects elements that have the specified attribute, regardless of its value.

Example 1

In the following example, we are using the jQuery [attribute] selector to select all the elements with the "name" attribute −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("input[name]").css("border", "2px solid blue");
        });
    </script>
</head>
<body>
    <input type="text" name="username" value="Varun">
    <input type="text" value="No Name Attribute">
    <input type="text" name="email" value="[email protected]">
</body>
</html>

After executing the above program, the elements with attribute "name" will be highlighted with solid blue border.

Example 2

In this example, we are selecting all the elements with a specific attribute value ("name = username") −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("input[name='username']").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <input type="text" name="username" value="Varun">
    <input type="text" name="email" value="[email protected]">
    <input type="text" name="username" value="Varun">
</body>
</html>

After executing the above program, all the elements with specific attribute value ("name = username") will be highlighted with yellow background color.

jquery_ref_selectors.htm
Advertisements