• jQuery Video Tutorials

jQuery #id Selector



The #id selector in jQuery is used to select an element with a specific id attribute. An id attribute must be unique within a document, ensuring that the #id selector targets a single, unique element.

The selector is case-sensitive, which means "#MyID" and "#myid" would select different elements if both existed.

Syntax

Following is the syntax of #id selector in jQuery −

$("#id")

Parameters

The id selector starts with a "#" followed by the id value of the element you want to select.

Example 1

In the following example, we are using the jquery #id selector to change the color of the text within a <div> element −

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("#demo").css("background-color", "yellow");
            })
        });
    </script>
</head>
<body>
    <div id="demo">This text will turn blue.</div>
    <button>Click</button>
</body>
</html>

When we execute the above program, the element with id="demo" changes its text background-color to yellow.

Example 2

In this example, we are changing the text content of a <p> element −

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("#demo").text("The text has been changed!");
            })
        });
    </script>
</head>
<body>
    <p id="demo">Hello mate, click the button below.</p>
    <button>Click</button>
</body>
</html>

When we click the button, the element with id="demo" changes its text content to "The text has been changed!".

Example 3

Here, we are using the jQuery #id selector to hide a <p> element −

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("#demo").hide();
            })
        });
    </script>
</head>
<body>
    <p id="demo">This paragraph will be hidden.</p>
    <button>Click</button>
</body>
</html>

After clicking the button, the element with id="demo" hides it using the hide() method.

jquery_ref_selectors.htm
Advertisements