jQuery ID Selector

Sheeraz Gul Feb 15, 2024
jQuery ID Selector

There are three types of selectors in jQuery; ID, Class, and Element. This tutorial demonstrates how to use the ID selector in jQuery.

jQuery ID Selector

The ID selector will select a single element with the given id attribute. The syntax is simple $(#ID), where the ID is the element ID.

If the ID contains special characters like periods or colons, we must escape those characters using backslashes. The ID selector returns the array filled with found elements.

For example:

  1. #DemoID will select a single element with the given ID.
  2. Div#DemoID will select a div with the given ID.

Let’s see an example of using the ID selector in jQuery.

<!DOCTYPE HTML>
<html>
    <head>
        <title>jQuery ID Selector</title>
        <script type = "text/javascript" src = "https://code.jquery.com/jquery-1.10.2.js"> </script>

        <script type = "text/javascript" language = "javascript">
            $(document).ready(function() {
                $("#DemoDiv1").css("background-color", "lightblue");
            });
        </script>
    </head>

    <body>
        <div id = "DemoDiv1">
            <p>This is the First Div.</p>
        </div>

        <div id = "DemoDiv2">
            <p>This is the Second Div.</p>
        </div>

        <div class = "DEMO1" id = "DemoDiv3">
            <p>This is the Third Div.</p>
        </div>
		<div class = "DEMO2" id = "DemoDiv1">
            <p>This is the Fourth Div.</p>
        </div>
    </body>
</html>

The code above will select the element with a unique ID and change its background color; as this code has two elements with the same ID, it will only select the first because the ID is always unique. See output:

jQuery ID Selector

Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

Related Article - jQuery Selector