How to write shorthand for document.getElementById() method in JavaScript ?
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 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 1: In this example, a function is created which returns the document.getElementById(‘idName’).
<!DOCTYPE HTML> < html > < head > < title > How to write shorthand for document.getElementById() method in JavaScript ? </ title > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;" > </ p > < button onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;" > </ 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 > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button:
Approach 2:
- Define a prototype = document.getElementById.
- Use this prototype by passing IDName as the first and only argument inplace of document.getElementById.
Example 2: In this example, a HTMLDocument Prototype is created which then used to select the element by IDName.
<!DOCTYPE HTML> < html > < head > < title > How to write shorthand for document.getElementById() method in JavaScript ? </ title > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;" > </ p > < button onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;" > </ 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 > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button: