Is there any shorthand for the JavaScript document.getElementById? Or is there any way I can define one? It gets repetitive retyping that over and over.
- 7I don't know who downvoted them, but someone who is unfamiliar enough with Javascript that he doesn't know how to create shortcuts like this is also likely to hit problems when he tries to use it with, say, jQuery, and finds that the $ variable is not consistent. The correct answer is "No, natively Javascript does not offer a shorthand, but there are several frameworks that make selecting DOM nodes easier."kojiro– kojiro2011-06-19 13:30:42 +00:00Commented Jun 19, 2011 at 13:30
24 Answers
var $ = function( id ) { return document.getElementById( id ); }; $( 'someID' ) Here I used $, but you can use any valid variable name.
var byId = function( id ) { return document.getElementById( id ); }; byId( 'someID' ) 16 Comments
$, congratulations on choosing that too?"$ if you never load them.var $ = document.getElementById.bind(document), but bind isn't available in all browsers. Perhaps it's faster though, because I'm only using native methods. Just wanted to add this.To save an extra character you could pollute the String prototype like this:
pollutePrototype(String, '绎', { configurable: false, // others must fail get: function() { return document.getElementById(this); }, set: function(element) { element.id = this; } }); function pollutePrototype(buildIn, name, descr) { var oldDescr = Object.getOwnPropertyDescriptor(buildIn.prototype, name); if (oldDescr && !oldDescr.configurable) { console.error('Unable to replace ' + buildIn.name + '.prototype.' + name + '!'); } else { if (oldDescr) { console.warn('Replacing ' + buildIn.name + '.prototype.' + name + ' might cause unexpected behaviour.'); } Object.defineProperty(buildIn.prototype, name, descr); } } It works in some browsers and you can access elements this way:
document.body.appendChild( 'footer'.绎 = document.createElement('div') ); 'footer'.绎.textContent = 'btw nice browser :)'; I have chosen the name of the property almost randomly. If you actually wanted to use this shorthand I would suggest coming up with something easier to type.
8 Comments
You can easily create shorthand easily yourself:
function getE(id){ return document.getElementById(id); } 3 Comments
id's are saved to the window.
HTML
<div id='logo'>logo</div> JS
logo.innerHTML; is the same as writing:
document.getElementById( 'logo' ).innerHtml; I don't suggest using the former method as it is not common practice.
3 Comments
<div id="location"></div> and calling window.location will not work.A quick alternative to contribute:
HTMLDocument.prototype.e = document.getElementById Then just do:
document.e('id'); There's a catch, it doesn't work in browsers that don't let you extend prototypes (e.g. IE6).
5 Comments
prototype.js which did exactly this same thing.(Shorthand for not only getting element by ID, but also getting element by class :P)
I use something like
function _(s){ if(s.charAt(0)=='#')return [document.getElementById(s.slice(1))]; else if(s.charAt(0)=='.'){ var b=[],a=document.getElementsByTagName("*"); for(i=0;i<a.length;i++)if(a[i].className.split(' ').indexOf(s.slice(1))>=0)b.push(a[i]); return b; } } Usage : _(".test") returns all elements with class name test, and _("#blah") returns an element with id blah.
2 Comments
document.querySelectorAll, instead of trying to emulate a part of the querySelectorAll method in a custom function.There are several good answers here and several are dancing around jQuery-like syntax, but not one mentions actually using jQuery. If you're not against trying it, check out jQuery. It let's you select elements super easy like this..
$('#elementId') $('.className') $('a') // all anchors on page $('inputs') // all inputs on page $('p a') // all anchors within paragaphs on page 3 Comments
I frequently use:
var byId='getElementById' var byClass='getElementsByClass' var byTag='getElementsByTag' var mydiv=document[byId]('div') /* as document["getElementById"] === document.getElementById */ I think it's better than a external function (e.g. $() or byId()) because you can do things like this:
var link=document[byId]('list')[byClass]('li')[0][byTag]('a')[0]
Btw, don't use jQuery for this, jQuery is much, much slower than document.getElementById(), an external function like $() or byId(), or my method: http://jsperf.com/document-getelementbyid-vs-jquery/5
Comments
Yes, it gets repetitive to use the same function over and over each time with a different argument:
var myImage = document.getElementById("myImage"); var myDiv = document.getElementById("myDiv"); So a nice thing would be a function that takes all those arguments at the same time:
function getElementsByIds(/* id1, id2, id3, ... */) { var elements = {}; for (var i = 0; i < arguments.length; i++) { elements[arguments[i]] = document.getElementById(arguments[i]); } return elements; } Then you would have references to all your elements stored in one object:
var el = getElementsByIds("myImage", "myDiv"); el.myImage.src = "test.gif"; But you would still have to list all those ids.
You could simplify it even more if you want all elements with ids:
function getElementsWithIds() { var elements = {}; var elementList = document.querySelectorAll("[id]"); for (var i = 0; i < elementList.length; i++) { elements[elementList[i].id] = elementList[i]; } return elements; } But it would be pretty expensive to call this function if you have many elements.
So, theoretically, if you would use the with keyword you could write code like this:
with (getElementsByIds('myButton', 'myImage', 'myTextbox')) { myButton.onclick = function() { myImage.src = myTextbox.value; }; } But I don't want to promote the use of with. Probably there's a better way to do it.
Comments
Well, you could create a shorthand function, that's what I do.
function $(element) { return document.getElementById(element); } and then when you wanted to get it, you just do
$('yourid') Also, another useful trick that I found, is that if you want to get the value or innerHTML of an item ID, you can make functions like this:
function $val(el) { return $(el).value; } function $inner(el) { return $(el).innerHTML; } Hope you like it!
I actually made a kind of mini javascript library based on this whole idea. Here it is.
1 Comment
I usually use something like this:
let byId = function(id){ return document.getElementById(id); let byClass = function(clas){ return document.querySelector(‘.&{clas}’); let byClassAll = function(clas){ return document.querySelectorAll(‘.&{clas}’); You can’t use class as parameter in the functions because it is reserved instead I use ”clas”
Comments
If this is on your own site, consider using a library like jQuery to give you this and many other useful shorthands that also abstract away browser differences. Personally, if I wrote enough code to be bothered by the longhand, I would include jQuery.
In jQuery, the syntax would be $("#someid"). If you then want the actual DOM element and not the jQuery wrapper, it's $("#someid")[0], but you could most likely do whatever you're after with the jQuery wrapper.
Or, if you're using this in a browser developer console, research their built-in utilities. As someone else mentioned, the Chrome JavaScript console includes a $("someid") method, and you can also click an element in the developer tools "Elements" view and then reference it with $0 from the console. The previously selected element becomes $1 and so on.
Comments
If the only issue here is typing, maybe you should just get yourself a JavaScript editor with intellisense.
If the purpose is to get shorter code, then you could consider a JavaScript library like jQuery, or you can just write your own shorthand functions, like:
function byId(string) {return document.getElementById(string);} I used to do the above for better performance. What I learnt last year is that with compression techniques the server does it automatically for you, so my shortening technique was actually making my code heavier. Now I am just happy with typing the whole document.getElementById.
Comments
If you are asking for a shorthand function...
<!DOCTYPE html> <html> <body> The content of the body element is displayed in your browser. <div id="d1">DIV</div> <script> var d=document; d.g=document.getElementById; d.g("d1").innerHTML = "catch"; </script> </body> </html> or
<!DOCTYPE html> <html> <body> The content of the body element is displayed in your browser. <div id="d1">DIV</div> <script> var w=window; w["d1"].innerHTML = "catch2"; </script> </body> Comments
Arrow functions make is shorter.
var $id = (id) => document.getElementById(id); 1 Comment
id argument.wrap the document.querySelectorAll ... a jquery like select
function $(selector){ var s = document.querySelectorAll(selector); return s.length > 1 ? s : s[0]; } // usage: $('$myId') 1 Comment
$('#myId') then it should usually return that HTMLElement, because you hopefully assigned that id exactly once. But if you would use it with queries that might match multiple elements it gets cumbersome.You can use a wrapper function like :
const byId = (id) => document.getElementById(id); Or
Assign document.getElementById to a variable by binding it with document object.
const byId = document.getElementById.bind(document); Note: In second approach, If you don't bind document.getElementById with document you'll get error :
Uncaught TypeError: Illegal invocation What Function.bind does is it creates a new function with its this keyword set to value that you provide as argument to Function.bind.
Read docs for Function.bind
Comments
Well, if the id of the element does not compete with any properties of the global object, you don't have to use any function.
myDiv.appendChild(document.createTextNode("Once I was myDiv. ")); myDiv.id = "yourDiv"; yourDiv.appendChild(document.createTextNode("But now I'm yourDiv.")); edit: But you don't want to make use of this 'feature'.
4 Comments
Another wrapper:
const IDS = new Proxy({}, { get: function(target, id) { return document.getElementById(id); } }); IDS.camelCaseId.style.color = 'red'; IDS['dash-id'].style.color = 'blue'; <div id="camelCaseId">div 1</div> <div id="dash-id">div 2</div> This, in case you don't want to use the unthinkable, see above.
Comments
I just use: function id(id) {return document.getElementById(id);}", called by id(target id).action; It works for me in Chrome, Edge & Firefox, though not in Safari or Opera.
2 Comments
I wrote this yesterday and found it quite useful.
function gid(id, attribute) { var x = 'document.getElementById("'+id+'")'; if(attribute) x += '.'+attribute; eval('x =' + x); return x; } This is how you use it.
// Get element by ID var node = gid('someID'); //returns <p id='someID' class='style'>Hello World</p> // returns 'Hello World' // var getText = document.GetElementById('someID').innerText; var getText = gid('someID', 'innerText'); // Get parent node var parentNode = gid('someID', 'parentNode');