使用jQuery获取元素类列表。

时间:2022-11-28 09:26:44

Is there a way in jQuery to loop through or assign to an array all of the classes that are assigned to an element?

在jQuery中是否有一种方法可以将分配给元素的所有类循环或分配给一个数组?

ex.

前女友。

<div class="Lorem ipsum dolor_spec sit amet">Hello World!</div>

I will be looking for a "special" class as in "dolor_spec" above. I know that I could use hasClass() but the actual class name may not necessarily be known at the time.

我将在上面的“dolor_spec”中寻找一个“特殊”类。我知道我可以使用hasClass(),但是实际的类名在当时可能并不一定是已知的。

17 个解决方案

#1


631  

You can use document.getElementById('divId').className.split(/\s+/); to get you an array of class names.

您可以使用. getelementbyid(divId).className.split(/ \ s + /;获取类名数组。

Then you can iterate and find the one you want.

然后您可以迭代并找到您想要的。

var classList = document.getElementById('divId').className.split(/\s+/);
for (var i = 0; i < classList.length; i++) {
    if (classList[i] === 'someClass') {
        //do something
    }
}

jQuery does not really help you here...

jQuery并不能真正帮助您……

var classList = $('#divId').attr('class').split(/\s+/);
$.each(classList, function(index, item) {
    if (item === 'someClass') {
        //do something
    }
});

#2


217  

Why has no one simply listed.

为什么没有人简单地列出。

$(element).attr("class").split(' ');

#3


133  

Here is a jQuery plugin which will return an array of all the classes the matched element(s) have

这是一个jQuery插件,它将返回匹配元素拥有的所有类的数组

;!(function ($) {
    $.fn.classes = function (callback) {
        var classes = [];
        $.each(this, function (i, v) {
            var splitClassName = v.className.split(/\s+/);
            for (var j = 0; j < splitClassName.length; j++) {
                var className = splitClassName[j];
                if (-1 === classes.indexOf(className)) {
                    classes.push(className);
                }
            }
        });
        if ('function' === typeof callback) {
            for (var i in classes) {
                callback(classes[i]);
            }
        }
        return classes;
    };
})(jQuery);

Use it like

喜欢使用它

$('div').classes();

In your case returns

在你的情况中返回

["Lorem", "ipsum", "dolor_spec", "sit", "amet"]

You can also pass a function to the method to be called on each class

您还可以将一个函数传递给要在每个类上调用的方法

$('div').classes(
    function(c) {
        // do something with each class
    }
);

Here is a jsFiddle I set up to demonstrate and test http://jsfiddle.net/GD8Qn/8/

下面是我设置的用于演示和测试http://jsfiddle.net/GD8Qn/8/的jsFiddle

Minified Javascript

;!function(e){e.fn.classes=function(t){var n=[];e.each(this,function(e,t){var r=t.className.split(/\s+/);for(var i in r){var s=r[i];if(-1===n.indexOf(s)){n.push(s)}}});if("function"===typeof t){for(var r in n){t(n[r])}}return n}}(jQuery);

#4


109  

On supporting browsers, you can use DOM elements' classList property.

在支持浏览器上,可以使用DOM元素的classList属性。

$(element)[0].classList

It is an array-like object listing all of the classes the element has.

它是一个类数组的对象,列出了元素的所有类。

If you need to support old browser versions that don't support the classList property, the linked MDN page also includes a shim for it - although even the shim won't work on Internet Explorer versions below IE 8.

如果您需要支持不支持classList属性的旧浏览器版本,那么链接的MDN页面也为它提供了一个shim—尽管即使是shim也不能在IE 8下面的Internet Explorer版本上工作。

#5


47  

You should try this one:

你应该试试这个:

$("selector").prop("classList")

It returns an array of all current classes of the element.

它返回元素的所有当前类的数组。

#6


14  

var classList = $(element).attr('class').split(/\s+/);
$(classList).each(function(index){

     //do something

});

#7


7  

$('div').attr('class').split(' ').map(function(cls){ console.log(cls);})

#8


4  

Update:

更新:

As @Ryan Leonard pointed out correctly, my answer doesn't really fix the point I made my self... You need to both trim and remove double spaces with (for example) string.replace(/ +/g, " ").. Or you could split the el.className and then remove empty values with (for example) arr.filter(Boolean).

正如@Ryan Leonard正确指出的那样,我的回答并不能真正解决我自己的问题……您需要用(例如)字符串修剪和删除双空格。替换(/ + / g”、“). .或者你可以拆分el。然后用(例如)arr.filter(布尔)删除空值。

const classes = element.className.split(' ').filter(Boolean);

or more modern

或者更现代

const classes = element.classList;

Old:

旧:

With all the given answers, you should never forget to user .trim() (or $.trim())

对于所有给定的答案,您不应该忘记用户.trim()(或$.trim())

Because classes gets added and removed, it can happen that there are multiple spaces between class string.. e.g. 'class1 class2       class3'..

因为类被添加和删除,所以类字符串之间可能有多个空格。如。“class1 class2 class3”. .

This would turn into ['class1', 'class2','','','', 'class3']..

这将变成[‘class1’,‘class2’,”、“,”、“class3”)。

When you use trim, all multiple spaces get removed..

当你使用修剪,所有的多重空间被删除。

#9


3  

Might this can help you too. I have used this function to get classes of childern element..

也许这也能帮助你。我用这个函数得到了childern元素的类。

function getClickClicked(){
    var clickedElement=null;
    var classes = null;<--- this is array
    ELEMENT.on("click",function(e){//<-- where element can div,p span, or any id also a class
        clickedElement = $(e.target);
        classes = clickedElement.attr("class").split(" ");
        for(var i = 0; i<classes.length;i++){
            console.log(classes[i]);
        }
        e.preventDefault();
    });
}

In your case you want doler_ipsum class u can do like this now calsses[2];.

在您希望使用doler_ipsum类u的情况下,可以这样做,现在将其命名为[2];

#10


2  

Try This. This will get you the names of all the classes from all the elements of document.

试试这个。这将从文档的所有元素中获取所有类的名称。

$(document).ready(function() {
var currentHtml="";
$('*').each(function() {
    if ($(this).hasClass('') === false) {
        var class_name = $(this).attr('class');
        if (class_name.match(/\s/g)){
            var newClasses= class_name.split(' ');
            for (var i = 0; i <= newClasses.length - 1; i++) {
                if (currentHtml.indexOf(newClasses[i]) <0) {
                    currentHtml += "."+newClasses[i]+"<br>{<br><br>}<br>"
                }
            }
        }
        else
        {
            if (currentHtml.indexOf(class_name) <0) {
                currentHtml += "."+class_name+"<br>{<br><br>}<br>"
            }
        }
    }
    else
    {
        console.log("none");
    }
});
$("#Test").html(currentHtml);

});

});

Here is the working example: https://jsfiddle.net/raju_sumit/2xu1ujoy/3/

这里有一个工作示例:https://jsfiddle.net/raju_sumit/2xu1ujoy/3/

#11


1  

Thanks for this - I was having a similar issue, as I'm trying to programatically relate objects will hierarchical class names, even though those names might not necessarily be known to my script.

感谢这一点——我遇到了类似的问题,因为我正在尝试以编程的方式关联对象将具有层次性的类名,尽管我的脚本不一定知道这些名称。

In my script, I want an <a> tag to turn help text on/off by giving the <a> tag [some_class] plus the class of toggle, and then giving it's help text the class of [some_class]_toggle. This code is successfully finding the related elements using jQuery:

在我的脚本中,我希望一个标记通过提供标记[some_class]和toggle类来打开/关闭帮助文本,然后为它提供帮助文本[some_class]_toggle的类。本代码使用jQuery成功找到相关元素:

$("a.toggle").toggle(function(){toggleHelp($(this), false);}, function(){toggleHelp($(this), true);});

function toggleHelp(obj, mode){
    var classList = obj.attr('class').split(/\s+/);
    $.each( classList, function(index, item){
    if (item.indexOf("_toggle") > 0) {
       var targetClass = "." + item.replace("_toggle", "");
       if(mode===false){$(targetClass).removeClass("off");}
       else{$(targetClass).addClass("off");}
    }
    });
} 

#12


0  

javascript provides a classList attribute for a node element in dom. Simply using

javascript为dom中的节点元素提供了一个classList属性。简单的使用

  element.classList

will return a object of form

将返回一个窗体对象吗

  DOMTokenList {0: "class1", 1: "class2", 2: "class3", length: 3, item: function, contains: function, add: function, remove: function…}

The object has functions like contains, add, remove which you can use

该对象具有包含、添加、删除等可以使用的函数

#13


0  

I had a similar issue, for an element of type image. I needed to check whether the element was of a certain class. First I tried with:

我有一个类似的问题,关于类型为image的元素。我需要检查元素是否属于某个类。首先我尝试:

$('<img>').hasClass("nameOfMyClass"); 

but I got a nice "this function is not available for this element".

但是我得到了一个很好的“这个函数不能用于这个元素”。

Then I inspected my element on the DOM explorer and I saw a very nice attribute that I could use: className. It contained the names of all the classes of my element separated by blank spaces.

然后我在DOM explorer上检查了我的元素,我看到了一个很好的属性,我可以使用:className。它包含由空格分隔的元素的所有类的名称。

$('img').className // it contains "class1 class2 class3"

Once you get this, just split the string as usual.

一旦你得到这个,就像往常一样分割字符串。

In my case this worked:

在我的例子中,这行得通:

var listOfClassesOfMyElement= $('img').className.split(" ");

I am assuming this would work with other kinds of elements (besides img).

我假设这将与其他类型的元素(除了img)一起工作。

Hope it helps.

希望它可以帮助。

#14


-3  

A bit late, but using the extend() function lets you call "hasClass()" on any element, e.g.:
var hasClass = $('#divId').hasClass('someClass');

有点晚了,但是使用extend()函数可以在任何元素上调用“hasClass()”,例如:var hasClass = $('#divId').hasClass('someClass');

(function($) {
$.extend({
    hasClass: new function(className) {
        var classAttr = $J(this).attr('class');
        if (classAttr != null && classAttr != undefined) {
            var classList = classAttr.split(/\s+/);
            for(var ix = 0, len = classList.length;ix < len;ix++) {
                if (className === classList[ix]) {
                    return true;
                }
            }
        }
        return false;
    }
}); })(jQuery);

#15


-3  

The question is what Jquery is designed to do.

问题是Jquery的设计目的是什么。

$('.dolor_spec').each(function(){ //do stuff

And why has no one given .find() as an answer?

为什么没有人给出。find()作为答案呢?

$('div').find('.dolor_spec').each(function(){
  ..
});

There is also classList for non-IE browsers:

也有非ie浏览器的类列表:

if element.classList.contains("dolor_spec") {  //do stuff

#16


-4  

Here you go, just tweaked readsquare's answer to return an array of all classes:

这里,调整了readsquare的答案,返回所有类的数组:

function classList(elem){
   var classList = elem.attr('class').split(/\s+/);
    var classes = new Array(classList.length);
    $.each( classList, function(index, item){
        classes[index] = item;
    });

    return classes;
}

Pass a jQuery element to the function, so that a sample call will be:

将jQuery元素传递给函数,使示例调用为:

var myClasses = classList($('#myElement'));

#17


-4  

I know this is an old question but still.

我知道这是个老问题,但还是。

<div id="specId" class="Lorem ipsum dolor_spec sit amet">Hello World!</div>

var className=".dolor_spec" //dynamic

If you want to manipulate element

如果你想操作元素

$("#specId"+className).addClass('whatever');

If you want to check if element has class

如果要检查元素是否有类。

 $("#specId"+className).length>0

if multiple classes

如果多个类

//if you want to select ONE of the classes
var classNames = ['.dolor_spec','.test','.test2']
$("#specId"+classNames).addClass('whatever');
$("#specId"+classNames).length>0
//if you want to select all of the classes
var result = {className: ""};
classNames.forEach(function(el){this.className+=el;},result);
var searchedElement= $("#specId"+result.className);
searchedElement.addClass('whatever');
searchedElement.length>0

#1


631  

You can use document.getElementById('divId').className.split(/\s+/); to get you an array of class names.

您可以使用. getelementbyid(divId).className.split(/ \ s + /;获取类名数组。

Then you can iterate and find the one you want.

然后您可以迭代并找到您想要的。

var classList = document.getElementById('divId').className.split(/\s+/);
for (var i = 0; i < classList.length; i++) {
    if (classList[i] === 'someClass') {
        //do something
    }
}

jQuery does not really help you here...

jQuery并不能真正帮助您……

var classList = $('#divId').attr('class').split(/\s+/);
$.each(classList, function(index, item) {
    if (item === 'someClass') {
        //do something
    }
});

#2


217  

Why has no one simply listed.

为什么没有人简单地列出。

$(element).attr("class").split(' ');

#3


133  

Here is a jQuery plugin which will return an array of all the classes the matched element(s) have

这是一个jQuery插件,它将返回匹配元素拥有的所有类的数组

;!(function ($) {
    $.fn.classes = function (callback) {
        var classes = [];
        $.each(this, function (i, v) {
            var splitClassName = v.className.split(/\s+/);
            for (var j = 0; j < splitClassName.length; j++) {
                var className = splitClassName[j];
                if (-1 === classes.indexOf(className)) {
                    classes.push(className);
                }
            }
        });
        if ('function' === typeof callback) {
            for (var i in classes) {
                callback(classes[i]);
            }
        }
        return classes;
    };
})(jQuery);

Use it like

喜欢使用它

$('div').classes();

In your case returns

在你的情况中返回

["Lorem", "ipsum", "dolor_spec", "sit", "amet"]

You can also pass a function to the method to be called on each class

您还可以将一个函数传递给要在每个类上调用的方法

$('div').classes(
    function(c) {
        // do something with each class
    }
);

Here is a jsFiddle I set up to demonstrate and test http://jsfiddle.net/GD8Qn/8/

下面是我设置的用于演示和测试http://jsfiddle.net/GD8Qn/8/的jsFiddle

Minified Javascript

;!function(e){e.fn.classes=function(t){var n=[];e.each(this,function(e,t){var r=t.className.split(/\s+/);for(var i in r){var s=r[i];if(-1===n.indexOf(s)){n.push(s)}}});if("function"===typeof t){for(var r in n){t(n[r])}}return n}}(jQuery);

#4


109  

On supporting browsers, you can use DOM elements' classList property.

在支持浏览器上,可以使用DOM元素的classList属性。

$(element)[0].classList

It is an array-like object listing all of the classes the element has.

它是一个类数组的对象,列出了元素的所有类。

If you need to support old browser versions that don't support the classList property, the linked MDN page also includes a shim for it - although even the shim won't work on Internet Explorer versions below IE 8.

如果您需要支持不支持classList属性的旧浏览器版本,那么链接的MDN页面也为它提供了一个shim—尽管即使是shim也不能在IE 8下面的Internet Explorer版本上工作。

#5


47  

You should try this one:

你应该试试这个:

$("selector").prop("classList")

It returns an array of all current classes of the element.

它返回元素的所有当前类的数组。

#6


14  

var classList = $(element).attr('class').split(/\s+/);
$(classList).each(function(index){

     //do something

});

#7


7  

$('div').attr('class').split(' ').map(function(cls){ console.log(cls);})

#8


4  

Update:

更新:

As @Ryan Leonard pointed out correctly, my answer doesn't really fix the point I made my self... You need to both trim and remove double spaces with (for example) string.replace(/ +/g, " ").. Or you could split the el.className and then remove empty values with (for example) arr.filter(Boolean).

正如@Ryan Leonard正确指出的那样,我的回答并不能真正解决我自己的问题……您需要用(例如)字符串修剪和删除双空格。替换(/ + / g”、“). .或者你可以拆分el。然后用(例如)arr.filter(布尔)删除空值。

const classes = element.className.split(' ').filter(Boolean);

or more modern

或者更现代

const classes = element.classList;

Old:

旧:

With all the given answers, you should never forget to user .trim() (or $.trim())

对于所有给定的答案,您不应该忘记用户.trim()(或$.trim())

Because classes gets added and removed, it can happen that there are multiple spaces between class string.. e.g. 'class1 class2       class3'..

因为类被添加和删除,所以类字符串之间可能有多个空格。如。“class1 class2 class3”. .

This would turn into ['class1', 'class2','','','', 'class3']..

这将变成[‘class1’,‘class2’,”、“,”、“class3”)。

When you use trim, all multiple spaces get removed..

当你使用修剪,所有的多重空间被删除。

#9


3  

Might this can help you too. I have used this function to get classes of childern element..

也许这也能帮助你。我用这个函数得到了childern元素的类。

function getClickClicked(){
    var clickedElement=null;
    var classes = null;<--- this is array
    ELEMENT.on("click",function(e){//<-- where element can div,p span, or any id also a class
        clickedElement = $(e.target);
        classes = clickedElement.attr("class").split(" ");
        for(var i = 0; i<classes.length;i++){
            console.log(classes[i]);
        }
        e.preventDefault();
    });
}

In your case you want doler_ipsum class u can do like this now calsses[2];.

在您希望使用doler_ipsum类u的情况下,可以这样做,现在将其命名为[2];

#10


2  

Try This. This will get you the names of all the classes from all the elements of document.

试试这个。这将从文档的所有元素中获取所有类的名称。

$(document).ready(function() {
var currentHtml="";
$('*').each(function() {
    if ($(this).hasClass('') === false) {
        var class_name = $(this).attr('class');
        if (class_name.match(/\s/g)){
            var newClasses= class_name.split(' ');
            for (var i = 0; i <= newClasses.length - 1; i++) {
                if (currentHtml.indexOf(newClasses[i]) <0) {
                    currentHtml += "."+newClasses[i]+"<br>{<br><br>}<br>"
                }
            }
        }
        else
        {
            if (currentHtml.indexOf(class_name) <0) {
                currentHtml += "."+class_name+"<br>{<br><br>}<br>"
            }
        }
    }
    else
    {
        console.log("none");
    }
});
$("#Test").html(currentHtml);

});

});

Here is the working example: https://jsfiddle.net/raju_sumit/2xu1ujoy/3/

这里有一个工作示例:https://jsfiddle.net/raju_sumit/2xu1ujoy/3/

#11


1  

Thanks for this - I was having a similar issue, as I'm trying to programatically relate objects will hierarchical class names, even though those names might not necessarily be known to my script.

感谢这一点——我遇到了类似的问题,因为我正在尝试以编程的方式关联对象将具有层次性的类名,尽管我的脚本不一定知道这些名称。

In my script, I want an <a> tag to turn help text on/off by giving the <a> tag [some_class] plus the class of toggle, and then giving it's help text the class of [some_class]_toggle. This code is successfully finding the related elements using jQuery:

在我的脚本中,我希望一个标记通过提供标记[some_class]和toggle类来打开/关闭帮助文本,然后为它提供帮助文本[some_class]_toggle的类。本代码使用jQuery成功找到相关元素:

$("a.toggle").toggle(function(){toggleHelp($(this), false);}, function(){toggleHelp($(this), true);});

function toggleHelp(obj, mode){
    var classList = obj.attr('class').split(/\s+/);
    $.each( classList, function(index, item){
    if (item.indexOf("_toggle") > 0) {
       var targetClass = "." + item.replace("_toggle", "");
       if(mode===false){$(targetClass).removeClass("off");}
       else{$(targetClass).addClass("off");}
    }
    });
} 

#12


0  

javascript provides a classList attribute for a node element in dom. Simply using

javascript为dom中的节点元素提供了一个classList属性。简单的使用

  element.classList

will return a object of form

将返回一个窗体对象吗

  DOMTokenList {0: "class1", 1: "class2", 2: "class3", length: 3, item: function, contains: function, add: function, remove: function…}

The object has functions like contains, add, remove which you can use

该对象具有包含、添加、删除等可以使用的函数

#13


0  

I had a similar issue, for an element of type image. I needed to check whether the element was of a certain class. First I tried with:

我有一个类似的问题,关于类型为image的元素。我需要检查元素是否属于某个类。首先我尝试:

$('<img>').hasClass("nameOfMyClass"); 

but I got a nice "this function is not available for this element".

但是我得到了一个很好的“这个函数不能用于这个元素”。

Then I inspected my element on the DOM explorer and I saw a very nice attribute that I could use: className. It contained the names of all the classes of my element separated by blank spaces.

然后我在DOM explorer上检查了我的元素,我看到了一个很好的属性,我可以使用:className。它包含由空格分隔的元素的所有类的名称。

$('img').className // it contains "class1 class2 class3"

Once you get this, just split the string as usual.

一旦你得到这个,就像往常一样分割字符串。

In my case this worked:

在我的例子中,这行得通:

var listOfClassesOfMyElement= $('img').className.split(" ");

I am assuming this would work with other kinds of elements (besides img).

我假设这将与其他类型的元素(除了img)一起工作。

Hope it helps.

希望它可以帮助。

#14


-3  

A bit late, but using the extend() function lets you call "hasClass()" on any element, e.g.:
var hasClass = $('#divId').hasClass('someClass');

有点晚了,但是使用extend()函数可以在任何元素上调用“hasClass()”,例如:var hasClass = $('#divId').hasClass('someClass');

(function($) {
$.extend({
    hasClass: new function(className) {
        var classAttr = $J(this).attr('class');
        if (classAttr != null && classAttr != undefined) {
            var classList = classAttr.split(/\s+/);
            for(var ix = 0, len = classList.length;ix < len;ix++) {
                if (className === classList[ix]) {
                    return true;
                }
            }
        }
        return false;
    }
}); })(jQuery);

#15


-3  

The question is what Jquery is designed to do.

问题是Jquery的设计目的是什么。

$('.dolor_spec').each(function(){ //do stuff

And why has no one given .find() as an answer?

为什么没有人给出。find()作为答案呢?

$('div').find('.dolor_spec').each(function(){
  ..
});

There is also classList for non-IE browsers:

也有非ie浏览器的类列表:

if element.classList.contains("dolor_spec") {  //do stuff

#16


-4  

Here you go, just tweaked readsquare's answer to return an array of all classes:

这里,调整了readsquare的答案,返回所有类的数组:

function classList(elem){
   var classList = elem.attr('class').split(/\s+/);
    var classes = new Array(classList.length);
    $.each( classList, function(index, item){
        classes[index] = item;
    });

    return classes;
}

Pass a jQuery element to the function, so that a sample call will be:

将jQuery元素传递给函数,使示例调用为:

var myClasses = classList($('#myElement'));

#17


-4  

I know this is an old question but still.

我知道这是个老问题,但还是。

<div id="specId" class="Lorem ipsum dolor_spec sit amet">Hello World!</div>

var className=".dolor_spec" //dynamic

If you want to manipulate element

如果你想操作元素

$("#specId"+className).addClass('whatever');

If you want to check if element has class

如果要检查元素是否有类。

 $("#specId"+className).length>0

if multiple classes

如果多个类

//if you want to select ONE of the classes
var classNames = ['.dolor_spec','.test','.test2']
$("#specId"+classNames).addClass('whatever');
$("#specId"+classNames).length>0
//if you want to select all of the classes
var result = {className: ""};
classNames.forEach(function(el){this.className+=el;},result);
var searchedElement= $("#specId"+result.className);
searchedElement.addClass('whatever');
searchedElement.length>0