The browser to document. GetElementById and other methods of the implementation of differences resolution

  • 2020-03-30 00:44:16
  • OfStack

All of my Web front end colleagues are familiar with document.getelementbyid. It is often used during development to get the element with a page id of xx, and since Prototype, the older JS library, became popular, people have preferred to abbreviate it this way


//Method 1
function $(id){ return document.getElementById(id); } 

Has anyone ever wondered why you write it this way instead of the following way?

//Way 2
var $ = document.getElementById; 

This is a much cleaner way to write $, and it makes sense to assign the document method getElementById to the variable $, and use $to get the element with the page id xx. In fact way 2 is feasible in IE6/7/8 (ie 9 some changes), Firefox/Safari/Chrome/Opera doesn't work. Please also test yourself.

Why Firefox/Safari/Chrome/Opera access 2 is no, because the browser getElementById method in the internal implementation relies on this (document), IE do not need this. Way or 2 in Firefox/Safari/Chrome/Opera called 'lost this, the following is a simple example


//Define a function show
function show(){alert(this.name);} 

//Define a p object with a name property
var p = {name:'Jack'}; 

show.call(p); // -> 'Jack' 
show(); // -> '' 
show.call(null); // -> ''<BR> 

You can see that the implementation of show relies on this (simply this is used in the body of the method), so the environment (execution context) at the time of the call (if there is no name attribute) does not get the desired result.
IE6/7/8, in other words, to achieve the document. The getElementById when not used this, ie 9 / Firefox/Safari/Chrome/Opera need to use this, this here is the document object. Direct call at 2 way this is within the window object, so cause way in Firefox 2 / Safari/Chrome/Opera cannot normal access elements according to the id.

After analyzing the case of getElementById, it's easy to see why some of the following methods differ from browser to browser


var prinf = document.write; 
prinf('<h3>Test prinf</h3>'); //Ie6/7/8 works, other browsers report an error

var prinfln = document.writeln; 
prinfln('<h3>Test prinfln</h3>'); //Ie6/7/8 works, other browsers report an error

var reload = location.reload; 
reload(); //Ie6/7/8 works, other browsers report an error

var go = history.go;  
go(-2); //Ie6/7/8 works, other browsers report an error


Related articles: