Javascript abbreviation for getElementById

Is there a shortcut for JavaScript document.getElementById? Or can I spot it? He receives repeated repetitions that are above and above .

+88
javascript
Jun 18 2018-11-18T00:
source share
20 answers
var $ = function( id ) { return document.getElementById( id ); }; $( 'someID' ) 

I used $ , but you can use any valid variable name.

 var byId = function( id ) { return document.getElementById( id ); }; byId( 'someID' ) 
+115
Jun 18 '11 at 20:44
source share

To preserve the extra character, you can pollute the String prototype as follows:

 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 the elements as follows:

 document.body.appendChild( 'footer'.็ปŽ = document.createElement('div') ); 'footer'.็ปŽ.textContent = 'btw nice browser :)'; 

I chose the name of the property almost randomly. If you really want to use this shorthand, I would suggest coming up with something easier to type.

+86
Jun 19 '11 at 3:18
source share

You can easily easily create a shorthand:

 function getE(id){ return document.getElementById(id); } 
+18
Jun 18 '11 at 20:45
source share

Quick alternative:

 HTMLDocument.prototype.e = document.getElementById 

Then just do:

 document.e('id'); 

There is a trick, it does not work in browsers that do not allow to extend prototypes (for example, IE6).

+14
Jun 19 '11 at 3:40
source share

(Abbreviation not only for obtaining an element by identifier, but also for receiving an 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 the class name test , and _("#blah") returns the element with id blah .

+8
Jun 19 2018-11-11T00:
source share
 <script> var _ = function(eId) { return getElementById(eId); } </script> <script> var myDiv = _('id'); </script> 
+6
Jun 18 '11 at 20:44
source share

There are some good answers here, and some dance around syntax like jQuery, but no one mentions using jQuery. If you don't mind this, check out jQuery . This allows you to select items very simply.

By ID :

 $('#elementId') 

By CSS class :

 $('.className') 

By item type :

 $('a') // all anchors on page $('inputs') // all inputs on page $('p a') // all anchors within paragaphs on page 
+6
Jun 18 2018-11-18T00:
source share

There is no built-in.

If you are not against pollution of the global namespace, why not:

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

EDIT - I changed the name of the function as something unusual, but short and did not come across otherwise with jQuery or anything else using the $ sign.

+5
Jun 18 '11 at 20:45
source share

id are saved in window .

HTML

  <div id='logo'>logo</div> 

Js

 logo.innerHTML; 

matches the entry:

 document.getElementById( 'logo' ).innerHtml; 

I do not suggest using the previous method, as this is not a common practice.

+5
May 13 '14 at 21:31
source share

Yes, it repeats in order to use the same function with and through each time with a different argument:

 var myImage = document.getElementById("myImage"); var myDiv = document.getElementById("myDiv"); 

So, a good thing would be a function that takes all these arguments at once:

 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 will have links to all your items stored in one object:

 var el = getElementsByIds("myImage", "myDiv"); el.myImage.src = "test.gif"; 

But you still have to list all of these identifiers.

You can simplify it even if you need all elements with identifiers:

 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 quite expensive to call this function if you have many elements.




So, theoretically, if you were to use the with keyword, you could write code like this:

 with (getElementsByIds('myButton', 'myImage', 'myTextbox')) { myButton.onclick = function() { myImage.src = myTextbox.value; }; } 

But I do not want to advertise using with . There is probably a better way to do this.

+3
Feb 17 '12 at 22:06
source share

Well, you can create a shorthand function that I do.

 function $(element) { return document.getElementById(element); } 

and then when you want to get it, you just do

 $('yourid') 

In addition, another useful trick I found is that if you want to get the value or innerHTML of the element identifier, you can perform the following functions:

 function $val(el) { return $(el).value; } function $inner(el) { return $(el).innerHTML; } 

I hope you will enjoy!

In fact, I created a kind of mini javascript library based on this idea. Here it is.

+2
Apr 09 '14 at 1:42 on
source share

I often use:

 var byId='getElementById' var byClass='getElementsByClass' var byTag='getElementsByTag' var mydiv=document[byId]('div') /* as document["getElementById"] === document.getElementById */ 

I think this is better than an 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 slower than document.getElementById() , an external function like $() or byId() , or my method: http://jsperf.com/document-getelementbyid-vs- jquery / 5

+2
Aug 04 '14 at 17:26
source share

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'); 
+2
Dec 23 '17 at 17:53 on
source share

If this is on your own site, consider using a library such as jQuery to give you this and many other useful shortcuts, which are also abstract in contrast to the browser. Personally, if I wrote enough code to worry about longhand, I would enable jQuery.

In jQuery, the syntax will be $("#someid") . If you need the actual DOM element and not the jQuery wrapper, then it is $("#someid")[0] , but you will most likely do everything you need with the jQuery wrapper.

Or, if you use this in your browserโ€™s developer console, check out their built-in utilities. As already mentioned, the Chrome JavaScript console includes the $("someid") method, and you can also click an element in the Elements view of the developer and then reference it using $0 from the console. The previously selected item becomes $1 , etc.

+1
Jun 19. '11 at 7:13
source share

If only the problem prints here, maybe you just need to get the JavaScript editor using intellisense.

If the goal is to get shorter code, then you can consider a JavaScript library such as jQuery, or just write your own shortened functions, for example:

 function byId(string) {return document.getElementById(string);} 

I used the above for better performance. What I learned last year is that using compression methods, the server does this automatically for you, so my reduction technique actually makes my code heavier. Now I'm just happy with the input of the entire document.getElementById document.

+1
Jan 21 2018-12-21T00:
source share

If you request 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; dg=document.getElementById; dg("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> 

+1
Nov 03 '14 at 8:33
source share

The functions of arrows are reduced.

 var $id = (id) => document.getElementById(id); 
+1
Sep 02 '15 at 12:58
source share

wrap document.querySelectorAll ... jquery as select

 function $(selector){ var s = document.querySelectorAll(selector); return s.length > 1 ? s : s[0]; } // usage: $('$myId') 
+1
Jan 16 '17 at 7:46 on
source share

Well, if the identifier of an element does not compete with any properties of the global object, you do not need 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 do not want to use this function.

0
Jun 20 '11 at 16:13
source share

Other shell:

 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, if you do not want to use the unthinkable , see above.

0
Jun 26. '18 at 21:58
source share



All Articles