- Published on
jQuery Like Selector in Pure JavaScript
- Authors
- Name
- Ashik Nesin
- @AshikNesin
Here's a quick post on how to select elements with the native HTML5 Selectors.
window.$ = function (s) {
return document[
{
'#': 'getElementById',
'.': 'getElementsByClassName',
'@': 'getElementsByName',
'=': 'getElementsByTagName',
}[s[0]] || 'querySelectorAll'
](s.slice(1));
};
It's based on the Michal Wachowski's gist
And here's how to use it.
// get by id
$('#iddiv');
// get by class name
$('.classdiv');
// get by element name
$('@namediv');
// get by element tag name
$('=div');
// get element by query selector
$('*div div.inside');
// getAttribute of name
$('#iddiv').getAttribute('name');
// getAttribute of name from nodelist
$('.classdiv')[0].getAttribute('name');