4

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.

2 Answers 2

3
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);
}
Sign up to request clarification or add additional context in comments.

10 Comments

why downvote.. atleast put a comment so that I could also understand
so, to check the third class for example, i could use var cl = element.classList; if(cl[3]=='class'){do something}?
@vinayakj For what it's worth, your answer looks fine to me and I upvoted it.
@TinyGiant Working in everything except IE9 seems like decent support to me, and you can always shim it to work with IE7, 8, and 9
|
1

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.