Skip to content
Related Articles
Open in App
Not now

Related Articles

How to write shorthand for document.getElementById() method in JavaScript ?

Improve Article
Save Article
Like Article
  • Last Updated : 19 Jan, 2023
Improve Article
Save Article
Like Article

The task is select the elements with id by using the shorthand for document.getElementById with the help of JavaScript. we’re going to discuss a few techniques.

 Approach 1:

  • Define a function that returns the document.getElementById(‘idName’).
  • This method takes IDName as the first and only argument.
  • Call the method with ID as the argument.

Example: In this example, a function is created which returns the document.getElementById(‘idName’)

html




<h1 style="color:green;">
    GeeksforGeeks
</h1>
  
<p id="GFG_UP">
</p>
  
<button onclick="GFG_Fun()">
    click here
</button>
  
<p id="GFG_DOWN">
</p>
  
<script>
    var ID = function(elementId) {
        return document.getElementById(elementId);
    };
      
    var el_up = ID("GFG_UP");
    var el_down = ID("GFG_DOWN");
      
    el_up.innerHTML = "Click on the button to select"
                + " the element by shorthand instead"
                + " of getElementById.";
      
    function GFG_Fun() {
        el_down.innerHTML = "Element selected by "
                + "shorthand of getElementById";
    }
</script>

Output:

How to write shorthand for document.getElementById() method in JavaScript ?

How to write shorthand for document.getElementById() method in JavaScript ?

Approach 2:

  • Define a prototype = document.getElementById.
  • Use this prototype by passing IDName as the first and only argument inplace of document.getElementById.

Example: In this example, a HTMLDocument Prototype is created which then used to select the element by IDName

html




<h1 style="color:green;">
    GeeksforGeeks
</h1>
  
<p id="GFG_UP">
</p>
  
<button onclick="GFG_Fun()">
    click here
</button>
  
<p id="GFG_DOWN">
</p>
  
<script>
    HTMLDocument.prototype.e = document.getElementById;
    var el_up = document.e("GFG_UP");
    var el_down = document.e("GFG_DOWN");
      
    el_up.innerHTML = "Click on the button to select"
            + " the element by shorthand instead of "
            + "getElementById.";
      
    function GFG_Fun() {
        el_down.innerHTML = "Element selected by "
                + "shorthand of getElementById";
    }
</script>

Output:

How to write shorthand for document.getElementById() method in JavaScript ?

How to write shorthand for document.getElementById() method in JavaScript ?


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!