Do everything with javascript

Nice way to check dom node className

It happen quite often to me that I need to check the element className in the event handler and to determine what function to trigger. element.className contains all the class name separated by space. e.g. “classA classB classCCC”. So it is bad to check the className like:

if (element.className === "classA") {...}

or

if (element.className.indexOf("classC") > -1) {...}

Sure we can do it with regular expression but there are faster way to do it.

I use YUI all the time and there is a YAHOO.util.Dom.hasClass, I read the source code and found they got a clever way to do it. It just add space in front and behide the className and do a indexOf. But one thing to note that you should not add the space to the className property directly instead you obtain a copy of the className string by getAttribute.

The code will look like:

function hasClass(el, class_to_match) {
    var c;
    if (el && el.className && typeof class_to_match === "string") {
        c = el.getAttribute("class");
        c = " "+ c + " ";
        return c.indexOf(" " + class_to_match + " ") > -1;
    } else {
        return false;
    }
}

Tidy and neat!

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>