Home >Web Front-end >JS Tutorial >The $ dollar sign is also used in JavaScript instead of document.getElementById_Basics

The $ dollar sign is also used in JavaScript instead of document.getElementById_Basics

WBOY
WBOYOriginal
2016-05-16 18:24:501436browse
Copy code The code is as follows:

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

The above is no problem for new versions of browsers. If you use an old browser, you can use the following function
Copy Code The code is as follows:

function $(objectId) {
if(document.getElementById && document.getElementById(objectId)) {
// W3C DOM
return document.getElementById(objectId);
}
else if (document.all && document.all(objectId)) {
// MSIE 4 DOM
return document.all (objectId);
}
else if (document.layers && document.layers[objectId]) {
// NN 4 DOM.. note: this won't find nested layers
return document .layers[objectId];
}
else {
return false;
}
}

to achieve the effect of $ replacing document.getElementById, although it is simple , but for those that do not reference frameworks such as prototype and jquery, there is no need to write document.getElementById every time, and it can be used everywhere after being defined in a public JavaScript file.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn