Skip to content
Related Articles

Related Articles

Improve Article

How to select element by ID in jQuery ?

  • Last Updated : 11 Sep, 2021
Geek Week

In this article, we are going to see how to select the element by its id using jQuery. To learn about this topic one should have prior knowledge about HTML, CSS, JavaScript and jQuery.

Using JavaScript: This question is also solved by a popular JavaScript method called document.getElementById() which is used to select the element by its id attribute. The getElementById() method returns the elements that has given ID which is passed to the function. This function is widely used in web designing to change the value of any particular element or get a particular element. If passed ID to the function does not exits then it returns null.

Syntax:

document.getElementById('idname') 

Example:

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>
        How do you select element by ID in javascript?
    </title>
</head>
  
<body style="border: 2px solid green; 
    min-height: 240px; text-align: center;">
      
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
      
    <p id="element" style="margin-top:20px;"></p>
  
    <script>
        setTimeout(function() {
            document.getElementById('element').innerText 
                = 'Hello Geeks !! Welcome to GeeksforGeeks';
        }, 2000);
    </script>
</body>
  
</html>


 



Output:

Using jQuery: The above code is also done by using jQuery method which is very simple and done with less code. The #id selector specifies an id for an element to be selected. It should not begin with a number and the id attribute must be unique within a document which means it can be used only one time.

syntax:

$("#idname");

Example:

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>
        How do you select element 
        by ID in javascript?
    </title>
      
    <script src=
    </script>
</head>
  
<body style="border: 2px solid green; 
    min-height: 240px; text-align: center;">
      
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
      
    <p id="element" style="margin-top:20px;"></p>
  
    <script>
        setTimeout(function () {
            $('#element').text(
                'Hello Geeks !! Welcome to GeeksforGeeks');
        }, 2000);
    </script>
</body>
  
</html>

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :