developer tip

jQuery로 요소에 대한 클래스 목록 가져 오기

copycodes 2020. 10. 2. 22:49
반응형

jQuery로 요소에 대한 클래스 목록 가져 오기


jQuery에서 요소에 할당 된 모든 클래스를 반복하거나 배열에 할당하는 방법이 있습니까?

전의.

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

위의 "dolor_spec"에서와 같이 "특별한"클래스를 찾고 있습니다. 나는 hasClass ()를 사용할 수 있다는 것을 알고 있지만 실제 클래스 이름은 당시에 반드시 알려지지 않을 수도 있습니다.


를 사용 document.getElementById('divId').className.split(/\s+/);하여 클래스 이름 배열을 얻을 수 있습니다 .

그런 다음 원하는 것을 반복하고 찾을 수 있습니다.

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

jQuery는 여기에서 실제로 도움이되지 않습니다 ...

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

왜 아무도 단순히 나열하지 않았습니다.

$(element).attr("class").split(/\s+/);

편집 : @MarkAmery가 지적했듯이 .split(' ')클래스 이름이 모든 종류의 공백으로 분리 될 수 있기 때문에 할 수 없습니다 .


다음은 일치하는 요소가 가진 모든 클래스의 배열을 반환하는 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);

그것을 사용하십시오

$('div').classes();

귀하의 경우 반품

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

각 클래스에서 호출 할 메서드에 함수를 전달할 수도 있습니다.

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

다음은 http://jsfiddle.net/GD8Qn/8/ 을 시연하고 테스트하기 위해 설정 한 jsFiddle입니다.

축소 된 자바 스크립트

;!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);

지원하는 브라우저에서 DOM 요소의 classList속성을 사용할 수 있습니다 .

$(element)[0].classList

요소가 가진 모든 클래스를 나열하는 배열과 같은 객체입니다.

classList속성을 지원하지 않는 이전 브라우저 버전을 지원해야하는 경우 연결된 MDN 페이지에 shim도 포함되어 있습니다. 그러나 shim도 IE 8 이하의 Internet Explorer 버전에서는 작동하지 않습니다.


다음 중 하나를 시도해야합니다.

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

요소의 모든 현재 클래스의 배열을 반환합니다.


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

     //do something

});

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

최신 정보:

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

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())

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

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

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


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

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


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");}
    }
    });
} 

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/


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


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:

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

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

Hope it helps.


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);

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

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'));

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

참고URL : https://stackoverflow.com/questions/1227286/get-class-list-for-element-with-jquery

반응형