开发者

jQuery: how to get all stylesheet classes+ids into an array

i'm using a wysiwyg editor which has a .css applied - how can i get all its classes into a variable eg. allClasses = ['navi','ma开发者_如何学Goin']?

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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜