I need to rewrite document.createElement() method and I'm looking for a javascript source code online to get some ideas. I searched http://code.google.com/p/v8/source/browse but it seems like the search returns results from all svn sources (even non-related libraries) which makes it messy. I browsed the code in the svn, and there are of course C++ source code, but obviously no javascript implementations.
You should not, and usually cannot, re-write native DOM methods. Methods such as createElement
are "close to the surface" of a client's EMACscript implementation, have protected scopes, and are simply not able to be reproduced by "userland" script.
In the case of createElement
, you might be able to overwrite the createElement
function of the document
object in certain browsers (see below), but you'll also quickly find that it crashes and burns on certain existing clients/versions. Further, you cannot change the prototype of document
because it has none.
You can, however, easily and without risk create a small wrapper function:
var createElement = function (ele_type, attrs) {
var ele = document.createElement(ele_type);
if (!ele)
return false;
for (var idx in attrs) {
if ((idx == 'styles' || idx == 'style') && typeof attrs[idx] == 'object') {
for (var prop in attrs[idx]){ele.style[prop] = attrs[idx][prop]}
} else if (idx == 'html') {
ele.innerHTML = attrs[idx]
} else {
ele.setAttribute(idx, attrs[idx]);
}
}
// now fire any custom events or do whatever you needed to do
};
var myNewDiv = createElement ('div', {'id':'myNewDiv', 'styles':{'color':'red'}});
That gives you the opportunity to implement custom code upon creation of a new element. It will work on all browsers regardless of implementation differences, and is as future-proof as any other code you would write today.
Another route mentioned above, which is NOT cross-browser or guaranteed to work even tomorrow, is to overwrite the createElement
function of active document
instance. The trouble with this approach is that the document object isn't defined by the specification -- it is implementation specific. Today, Firefox (for example) will allow you to overwrite this function, but that could change without notice.
document.createElement = function(originalDocumentCreate) {
return function() {
var ele = originalDocumentCreate.apply(this, arguments);
// now fire any custom events or do whatever you needed to do
return ele;
};
}(document.createElement);
See also: https://stackoverflow.com/a/11727842/610573 (code concept credit to Esailija)