Grupos de Google ya no admite publicaciones ni suscripciones nuevas de Usenet. El contenido anterior sigue visible.

Listing of all element's classes

12 vistas
Ir al primer mensaje no leído

Brian Herold

no leída,
28 jun 2006, 1:33:35 p.m.28/6/06
para
How can I get a list of all the css classes applied to an element?

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

Thanks

Matt Kruse

no leída,
28 jun 2006, 2:17:44 p.m.28/6/06
para

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

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


Ian Collins

no leída,
28 jun 2006, 5:27:01 p.m.28/6/06
para
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

no leída,
28 jun 2006, 6:39:44 p.m.28/6/06
para

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

no leída,
28 jun 2006, 7:14:33 p.m.28/6/06
para

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

no leída,
28 jun 2006, 11:25:49 p.m.28/6/06
para
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 mensajes nuevos