Reputation: 103
I have the following javascript code to put the uploader name before the upload date and view count 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 whole class attribute of a multiple class element? This didn't work:
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 would only get elements with exactly the given classes, and ignore ones that have MORE classes.
Upvotes: 4
Views: 1966
Reputation: 685
You can use classList
but this is not supported in all browsers.
I think the best solution is something like that:
function hasClass (element, cls) {
var classes = element.className.split(' ');
return classes.indexOf(cls) != -1;
}
Upvotes: 1
Reputation: 5681
element.classList
It would return you the array of all the classes present on the element
like ["site-icon", "favicon", "favicon-stackoverflow"]
, so then by using normal javascript you can implement hasClass functionality of your own.
So your hasClass function becomes
function hasClass(element, cls){
return element.classList.contains(cls);
}
Upvotes: 3