#943 bug
Jen Rawson

hasClassName returns true when class name is white space

Reported by Jen Rawson | November 23rd, 2009 @ 04:51 PM

The hasClassName method returns true when the className argument is a space and the class attribute for an element equals a space. Here is an example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <script src="scripts/prototype.js" type="text/javascript"></script>

  <h1 id="heading1" class=" ">Heading 1</h1>

  <script type="text/javascript" charset="utf-8">
    var el = $('heading1');
    alert(el.hasClassName(' '));


In Firefox and Internet Explorer the example above alerts "true". It does not make sense for the hasClassName method to return true for a space.

Also, in Internet Explorer 7, if the class attribute of an element contains a certain non-printable white space character, and that character is passed as an argument to hasClassName, the hasClassName method will return true. I came across this bug in my own development. I have an example case in my code base, however, I can not create a simple example to demonstrate or recreate the problem. I could not figure out exactly what non-printable white space character caused the problem.

My solution to both problems is to check if the className argument passed to the hasClassName method is blank. I added line 3 to the hasClassName method to perform this check:

  hasClassName: function(element, className) {
    if (!(element = $(element))) return;
    if(className.blank()) return false;
    var elementClassName = element.className;
    return (elementClassName.length > 0 && (elementClassName == className ||
      new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));

There may be a more optimal way to check for a blank class name argument but the code above does indeed solve the problem. It's interesting to note that the blank method also uses a regular expression. Another solution may be to incorporate this regular expression in to the hasClassName method.

Comments and changes to this ticket

Please Sign in or create a free account to add a new ticket.

With your very own profile, you can contribute to projects, track your activity, watch tickets, receive and update tickets through your email and much more.

New-ticket Create new ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile ยป

The Prototype JavaScript library.

Shared Ticket Bins