欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

jquery 得到 class name 得到 类名

shiping1 的头像









如何用Jquery获取某一个Div的Class或者ID

分类: JavaScript 28053人阅读 评论(1) 收藏 举报

有一个Div,我想获取其ID或者Class值。

那么我可以先定位到这个DIV,然后采用attr方法来获取其值:

假如说:有一段Html代码:

  1. <div class="comment" id="22">  
  2. <div class="comment_detail" style="display: block; ">  
  3. <div class="comment_my"><textarea class="comment_text" style="height: 16px; "></textarea></div>  
  4. <div class="comment_text_bottom" style="display: none; ">  
  5. <div class="comment_emotion"><a href="javascript:void(0)" class="comment_emotion_button">表情</a>  
  6. <div class="comment_emotion_detail" style="display: none; ">  
  7. </div>  
  8. </div>  
  9. <div class="comment_publish"><input class="submit" type="submit"  value="评论"></div>  
  10. </div>  
  11. </div>  
  12. <div class="comment_bar"><a href="javascript:void(0)" class="comment_click"></a></div>  
  13. </div>  

如果我想从submit处定位,获取到comment处DIv的ID,那么我就可以这样办:

ID值为:

[javascript] view plaincopy
  1. $(".submit").parent().parent().parent().parent().attr('id');  

其值为:22;

CLASS值为:
[javascript] view plaincopy
  1. $(".submit").parent().parent().parent().parent().attr('class')  
其值为:comment;
来自 http://blog.csdn.net/niuox/article/details/7299125


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

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.

shareimprove this question
 
2 
i have no idea about actually looping trough an existing collection, but i would getting the class attribute and use javascript, split it on the space... then you can loop over your array. –  Sander Aug 4 '09 at 12:43
   
If you don't know the class name at the time, preventing you from using hasClass(), how do you intend to know which one in the array it is? –  doomspork Aug 4 '09 at 13:05
   
I am designing a form where I am doing some preliminary validation with jQuery. I am appending the id of the input element to the class list of the error div if one is generated. I am then making it possible to click on the error div to focus the errant input element. This script is going to be used for more than one form. I therefore do not want to hard-code the ids in the script. –  Buggabill Aug 4 '09 at 13:10
   
Here is the code that I am using pastebin.com/m35dc280 –  Buggabill Aug 4 '09 at 13:13
1 
Right, I understand why you wouldn't want to hardcode. But if you take a moment to look over redsquare's example you'll see you've got to hardcode 'someClass' into the if block. Either way you could achieve this with a variable. –  doomspork Aug 4 '09 at 13:31
up vote414down voteaccepted

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

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.....

var classList =$('#divId').attr('class').split(/\s+/);
$.each( classList, function(index, item){
    if (item === 'someClass') {
       //do something
    }
});
shareimprove this answer
 
3 
that is exactly what i woud have done, but i was not sure if there was a build in jQuery function that gave you a collection of the classes. –  Sander Aug 4 '09 at 12:51
24 
FYI: jQuery uses className.split(/\s+/) –  David Kemp Feb 8 '10 at 11:56
4 
@WmasterJ The OP asked how to get all the classes defined on an element. How does hasClass help here! –  redsquare Jan 31 '11 at 9:19
32 
Add a jQuery plugin yourself: $.fn.classList = function() {return this.className.split(/\s+/);}; –  ripper234 Mar 9 '12 at 17:45
6 
@ripper234 You mean $.fn.classList = function() {return this[0].className.split(/\s+/);};, since className is not a property of the jQuery-wrapped DOM element. Your way results in TypeError: Cannot read property 'split' of undefined. Perhaps flag and ask a mod to edit your (popular but wrong) comment? –  Mark Amery Sep 3 '14 at 11:39 

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

;!(function ($) {
    $.fn.classes = function (callback) {
        var classes = [];
        $.each(this, function (i, v) {
            var splitClassName = v.className.split(/\s+/);
            for (var j in splitClassName) {
                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/

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);
shareimprove this answer
 
1 
Why a down vote? –  Will Jul 23 '12 at 2:02
12 
Here have an upvote –  MikeMurko Mar 1 '13 at 4:25
3 
This should have the most upvotes. –  alkis Apr 28 '13 at 22:39
2 
Thanks, maybe in 3 years this answer will surpass the current one haha. I went back and renamed my variables so they are readable and added a minified version. –  Will Apr 29 '13 at 19:15 
   
Perfect fit for FullCalendar when copying classes into the className attribute of an Event. –  Dan PowerAug 27 '13 at 15:46

Why has no one simply listed.

  $(element).attr("class").split(' ');
shareimprove this answer
 
4 
That is part of the accepted answer... I needed all the classes that were applied to an element. –  BuggabillApr 17 '12 at 12:26
   
Haha, true! I wanted just this. It returns a string of classes separated by spaces, so maybe if you want to pick up one of them you can split the string by space and get an array to pick up a class from –  Rahul DoleAug 6 '13 at 13:18
   
Perfect quick answer to the question without details. Perfect for others looking for the general answer to the general question. +1 –  Mike_K Jan 11 '14 at 19:19
   
nice answer +1. –  Adnan Ahmed Jun 16 '14 at 14:09
1 
Because it's wrong! Classes can be separated by any kind of whitespace (e.g. you can wrap a long class attribute in your HTML onto multiple lines), but this answer fails to account for that. Try pasting $('<div class="foo bar baz">').attr("class").split(' ') into your browser console (there's a tab character in there); you'll get ["foo", "bar baz"] instead of the correct class list of ["foo", "bar", "baz"]. – Mark Amery Dec 17 '14 at 23:27 

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

$(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.

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

     //do something

});
shareimprove this answer
 
$('div').attr('class').split(' ').map(function(cls){ console.log(cls);})
shareimprove this answer
 
   
This is a horrible abuse of .map; use .each if you don't need .map's return value. Splitting on spaces rather than any whitespace is also broken - see my comment on stackoverflow.com/a/10159062/1709587. Even if none of these points were true, this adds nothing new to the page. -1! –  Mark Amery Dec 17 '14 at 23:54 

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

  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

shareimprove this answer
 
   
Inferior duplicate of stackoverflow.com/a/5457148/1709587 which was posted 3 years before you; -1. – Mark Amery Dec 17 '14 at 23:52

A bit late, but using the extend() function lets you call "hasClass()" on any element, e.g.: 
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);
shareimprove this answer
 
8 
That was not the question. –  Tomas Mar 23 '11 at 13:18
5 
Also, jQuery has had this function built-in since version 1.2. –  Andrew Sep 15 '11 at 17:55

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:

$("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");}
    }
    });
} 
shareimprove this answer
 
   
Thanks Alan, I'm doing something similar, I'm surprised that there isn't a simpler way to do this. – Eric Kigathi Jan 31 '12 at 1:33
   
-​1 - tl;dr, goes off on a tangent not directly relevant to the question. –  Mark Amery Dec 17 '14 at 23:57

The question is what Jquery is designed to do.

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

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

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

There is also classList for non-IE browsers:

if element.classList.contains("dolor_spec") {  //do stuff
shareimprove this answer
 
1 
-​1; among other problems, your first two code snippets are unrelated to the question asked and your final snippet is a syntax error. –  Mark Amery Dec 17 '14 at 23:58

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

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:

var myClasses = classList($('#myElement'));
shareimprove this answer
 
3 
Why iterate through the classList array, add all elements to the classes array and return the classes array? Just returning the classList should do the same trick, right? –  Martijn Jul 28 '12 at 11:00
   
Nope. Since we are referring to a situation where there are many classes for the same element. If it was so easy, we weren't here on this thread :) –  Gregra Jul 29 '12 at 12:08 
8 
This thread is about returning a list of classes, and simply returning$(elem).attr('class').split(/\s+/) does that. Maybe I'm mistaking, but I don't see any reason to iterate through a collection, copy the contents to a new collection and return that new collection. –  MartijnJul 30 '12 at 9:26

普通分类: