Javascript Shorthand for getElementById

Javascript

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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' )

Solution 2 - Javascript

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.

Solution 3 - Javascript

You can easily create shorthand easily yourself:

function getE(id){
   return document.getElementById(id);
}

Solution 4 - Javascript

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).

Solution 5 - Javascript

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.

Solution 6 - Javascript

(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.

Solution 7 - Javascript

<script>
var _ = function(eId)
{
    return getElementById(eId);
}
</script>

<script>
var myDiv = _('id');
</script>

Solution 8 - Javascript

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..

By ID:

$('#elementId')

By CSS class:

$('.className')

By element type:

$('a')  // all anchors on page 
$('inputs')  // all inputs on page 
$('p a')  // all anchors within paragaphs on page 

Solution 9 - Javascript

There's none built-in.

If you don't mind polluting the global namespace, why not:

function $e(id) {
    return document.getElementById(id);
}

EDIT - I changed the function name to be something unusual, but short and not otherwise clashing with jQuery or anything else that uses a bare $ sign.

Solution 10 - Javascript

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

Solution 11 - Javascript

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.

Solution 12 - Javascript

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.

Solution 13 - Javascript

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.

Solution 14 - Javascript

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.

Solution 15 - Javascript

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>

Solution 16 - Javascript

Arrow functions make is shorter.

var $id = (id) => document.getElementById(id);

Solution 17 - Javascript

wrap the document.querySelectorAll ... a jquery like select

function $(selector){
   var s = document.querySelectorAll(selector); 
   return s.length > 1 ? s : s[0];
}

// usage: $('$myId')

Solution 18 - Javascript

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'.

Solution 19 - Javascript

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.

Solution 20 - Javascript

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

Solution 21 - Javascript

const $id = id => document.getElementById(id);
...
$id('header')

Solution 22 - Javascript

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');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontewView Question on Stackoverflow
Solution 1 - Javascriptuser113716View Answer on Stackoverflow
Solution 2 - JavascriptRobertView Answer on Stackoverflow
Solution 3 - JavascriptSarfrazView Answer on Stackoverflow
Solution 4 - JavascriptPablo FernandezView Answer on Stackoverflow
Solution 5 - Javascriptim_bentonView Answer on Stackoverflow
Solution 6 - JavascriptJiminPView Answer on Stackoverflow
Solution 7 - JavascriptgenesisView Answer on Stackoverflow
Solution 8 - JavascriptKonView Answer on Stackoverflow
Solution 9 - JavascriptAlnitakView Answer on Stackoverflow
Solution 10 - JavascriptGilles CastelView Answer on Stackoverflow
Solution 11 - JavascriptRobertView Answer on Stackoverflow
Solution 12 - Javascriptuser3385777View Answer on Stackoverflow
Solution 13 - JavascriptHenrik NView Answer on Stackoverflow
Solution 14 - JavascriptChristopheView Answer on Stackoverflow
Solution 15 - JavascriptLumicView Answer on Stackoverflow
Solution 16 - JavascriptwiktorView Answer on Stackoverflow
Solution 17 - Javascriptuser4602228View Answer on Stackoverflow
Solution 18 - JavascriptRobertView Answer on Stackoverflow
Solution 19 - JavascriptMike C.View Answer on Stackoverflow
Solution 20 - JavascriptOmkar76View Answer on Stackoverflow
Solution 21 - Javascriptgriffi-ghView Answer on Stackoverflow
Solution 22 - JavascriptBorn2die007View Answer on Stackoverflow