Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Listing of all element's classes

12 views
Skip to first unread message

Brian Herold

unread,
Jun 28, 2006, 1:33:35 PM6/28/06
to
How can I get a list of all the css classes applied to an element?

document.getElementById("someelement");
someelement.?(classlist)... blah

Thanks

Matt Kruse

unread,
Jun 28, 2006, 2:17:44 PM6/28/06
to

alert(document.getElementById('somelement').className);

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com


Ian Collins

unread,
Jun 28, 2006, 5:27:01 PM6/28/06
to
Brian Herold wrote:
> How can I get a list of all the css classes applied to an element?
>
An element only has one className attribute, do you want the styles? If
so, look up getComputedStyle() or for IE, currentStyle.

--
Ian Collins.

Brian Herold

unread,
Jun 28, 2006, 6:39:44 PM6/28/06
to

I ended up doing:

if(theElement.className.indexOf("somestyle") != -1) {
//code here
}

That way I can check if an element currently has a particular style
applied to it.

RobG

unread,
Jun 28, 2006, 7:14:33 PM6/28/06
to

Unless somestyle is a substring of some other style, in which case you
may get it wrong. Try using a regular expression and match whole
words:

var x = "fred blah tom";
var y = "blahfred blahblah blahtom";
var someClass = 'blah';
var classTest = new RegExp('\\b' + someClass + '\\b');
alert(
'Test: ' + classTest
+ '\n' + someClass + ' in ' + x + '? ' + classTest.test(x)
+ '\n' + someClass + ' in ' + y + '? ' + classTest.test(y)
);


Remember that an alement can have multiple class names in the className
attribute.


--
Rob

Matt Kruse

unread,
Jun 28, 2006, 11:25:49 PM6/28/06
to
RobG wrote:
> var classTest = new RegExp('\\b' + someClass + '\\b');

This is insufficient for class names like "a-b" which are, as far as I can
tell, allowed by the specs:
http://www.w3.org/TR/CSS21/syndata.html#q6

"In CSS 2.1, identifiers (including element names, classes, and IDs in
selectors) can contain only the characters [A-Za-z0-9] and ISO 10646
characters U+00A1 and higher, plus the hyphen (-) and the underscore (_);
they cannot start with a digit, or a hyphen followed by a digit."

In my util lib at http://www.javascripttoolbox.com/lib/util/ I use the
following code:

// Determine if an object or class string contains a given class.
css.hasClass = function(obj,className) {
if (!defined(obj) || obj==null || !RegExp) { return false; }
var re = new RegExp("(^|\\s)" + className + "(\\s|$)");
if (typeof(obj)=="string") {
return re.test(obj);
}
else if (typeof(obj)=="object" && obj.className) {
return re.test(obj.className);
}
return false;

0 new messages