hi,
i'm using a wysiwyg editor which has a .css applied - how can i get all its classes into a variable eg. allClasses = ['navi','main']?
thx
hi,
i'm using a wysiwyg editor which has a .css applied - how can i get all its classes into a variable eg. allClasses = ['navi','main']?
thx
Use the [id]
or [class]
selector. That selects all elements that have this attribute defined. Then just call attr('id')
on them and fetch the id.
(function($) {
$.fn.allAttributes = function(attrName) {
var selector = "[{attr}]".replace("{attr}", attrName);
var attributes = $(selector, this).map(function() {
return $(this).attr(attrName).split(' ');
});
attributes = $.unique(attributes);
return attributes;
};
})(jQuery);
This is a jQuery plugin that does exactly that. Example usage:
var ids = $("body").allAttributes("id");
var classes = $("body").allAttributes("class");
Some notes:
The function is calling split(' ')
because the class
attribute can have multiple CSS classes separated by a string such as "main navi footer"
. This separates them into separate items. $.unique
is called on the array at the end because class names could have been repeated at multiple places and I'm guessing you don't want duplicates.
Example here: http://jsfiddle.net/G4Pwc/