How to Get Element by ID in jQuery

Sheeraz Gul Feb 02, 2024
  1. Get Element By ID in JavaScript
  2. Get Element By ID in jQuery
How to Get Element by ID in jQuery

In JavaScript, we can use the method document.getElementById() to get the element by ID. In jQuery, we can use the $('#contents') to get the element by ID.

This tutorial demonstrates how to get elements by ID using both methods.

Get Element By ID in JavaScript

The document.getElementById() is the most popular method used to get elements by ID. This method is mostly used in web designing to change the value of an element or get that element.

The syntax for this method is:

document.getElementById('id')

Let’s try an example to get the element by ID using this method:

<!DOCTYPE html>
<html>
<head>
    <title>
        Select element by ID in javascript
    </title>
</head>

<body style="border: 4px solid blue; min-height: 300px; text-align: center;">

    <h1 style="color:blue;" id="delftstack">
        DELFTSTACK
    </h1>

    <script>
        setTimeout(function() {
            document.getElementById('delftstack').style.color = "green"
            }, 3000);
    </script>
</body>
</html>

The code above gets the h1 element ID and changes its color on a timeout. See output:

JavaScript Get Element by ID

Get Element By ID in jQuery

jQuery has an easier method to select an element by ID. jQuery has an ID selector which can select the element with a unique ID.

The syntax for this method is:

$("#idname");

Let’s try the example in jQuery, which will change the background of the element by getting it through the ID:

<!DOCTYPE html>
<html>

<head>
    <title>
    Select element by ID in JQuery
    </title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>

<body style="border: 4px solid blue; min-height: 300px; text-align: center;">

    <h1 style="color:blue;" id="delftstack">
        DELFTSTACK
    </h1>
    <script>
        setTimeout(function () {
            $('#delftstack').css("background-color", "yellow");;
        }, 3000);
    </script>
</body>
</html>

See the output for this code:

jQuery Get Element by ID

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 Element