JSFiddle - React, Tailwind, and code Playground
by Roman Zhak
HTML
<div class="hello st">1</div>
<div class="hello wake">2</div>
<div class="test st">3</div>
<span class="test st">4</span>
<span class="test st">5</span>
CSS
span {
display: block;
}
JavaScript
// Vanilla JS( Pure JS )
function byClass( name, node, tag ) {
var d = document
, context = node || d
, tag = tag || "*"
// set correct class
, classname = name.slice( 1 );
// check if native support exist
if( d.getElementsByClassName )
return context.getElementsByClassName( classname );
// for old browser
var all = context.getElementsByTagName("*")
, res = []
, length = all.length
, i = 0
, nameRexExp = new RegExp("(^|\\s)" + classname + "(\\s|$)");
if( !length ) return res;
if( length === 1 ) return nameRexExp.test(all[0]) &&
res.push(all[0]);
// filtering by class and tag
for( ; i < length; i++ ) {
var interim = all[i] ;
if( nameRexExp.test(interim.className) ) {
if( tag !== "*" ) {
tag = tag.toUpperCase();
if(interim.tagName.toUpperCase() !== tag) continue;
}
res.push( interim );
}
};
return res;
};
byClass(".test")
// end of Vanilla JS
// and jQuery only one line
$(".test")
// performance http://jsperf.com/get-by-class-performance