Open In App

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

The task is to 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:

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






<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>
        Write Shorthand for document.getElementById()
        method in JavaScript
    </title>
</head>
 
<body>
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
 
    <p>
        Click on the button to select the
        element by shorthand instead of
        getElementById
    </p>
 
    <button onclick="GFG_Fun()">
        click here
    </button>
 
    <p id="result"></p>
 
    <script>
        let ID = function (elementId) {
            return document.getElementById(elementId);
        };
 
        let res = ID("result");
 
        function GFG_Fun() {
            res.innerHTML = "Element selected by "
                + "shorthand of getElementById";
        }
    </script>
</body>
 
</html>

Output:

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

Approach 2:

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






<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>
        Write Shorthand for document.getElementById()
        method in JavaScript
    </title>
</head>
 
<body>
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
 
    <p>
        Click on the button to select the
        element by shorthand instead of
        getElementById
    </p>
 
    <button onclick="GFG_Fun()">
        click here
    </button>
 
    <p id="result"></p>
 
    <script>
        HTMLDocument.prototype.e = document.getElementById;
 
        let res = document.e("result");
 
        function GFG_Fun() {
            res.innerHTML = "Element selected by "
                + "shorthand of getElementById";
        }
    </script>
</body>
 
</html>

Output:

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


Article Tags :