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:
- 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
<!DOCTYPE html><html lang="en"><head> <title> Write Shorthand for document.getElementById() method in JavaScript </title></head><body> <h1 style="color:green;"> neveropen </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:
- Define a prototype = document.getElementById.
- Use this prototype by passing IDName as the first and only argument in-place of document.getElementById.
Example: In this example, a HTMLDocument Prototype is created which then used to select the element by IDName.
html
<!DOCTYPE html><html lang="en"><head> <title> Write Shorthand for document.getElementById() method in JavaScript </title></head><body> <h1 style="color:green;"> neveropen </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 ?
