How to check the class of multiple class elements in javascript, without jquery
I have the following javascript code to put uploader name before upload and view date in youtube search results.
function hasClass(element, cls) {
return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
var elems = document.getElementsByClassName('yt-lockup-meta-info');
var elemss = document.getElementsByClassName('yt-uix-sessionlink g-hovercard spf-link');
var elemsss = 1;
var elemssss = 0;
var myElem = document.getElementById('sb-button-notify');
if (myElem == null) elemsss = 0; // these two lines are here to skip the additional element
// that is only there if you are logged in
for (var i = 0; i < elems.length; ++i) {
if (hasClass(elemss[i+elemsss],'yt-uix-tile-link'))
{elemssss=elemssss+1;elemsss=elemsss+3;alert('damn');}
elems[i+elemssss].insertBefore(elemss[i+elemsss],elems[i+elemssss].firstChild);}
Instead of the hasClass function, how can I check the entire class attribute for an element with multiple classes? It did not help:
element.className=='yt-uix-sessionlink yt-uix-tile-link
yt-ui-ellipsis yt-ui-ellipsis-2 g-hovercard spf-link'
I just need to check the class, so the code can skip elements with a specific class. An even better solution would be an alternative to document.getElementsByClassName, which will only get elements with exactly specified classes and ignore those with better classes.
source to share
element.classList
It will return you an array of all the classes present in the element for example ["site-icon", "favicon", "favicon-stackoverflow"]
, so with plain javascript you can implement your own hasClass functions.
So your hasClass function becomes
function hasClass(element, cls){
return element.classList.contains(cls);
}
source to share