development

jQuery를 사용하여 클래스 이름 가져 오기

big-blog 2020. 10. 3. 11:14
반응형

jQuery를 사용하여 클래스 이름 가져 오기


jQuery를 사용하여 클래스 이름을 얻고 싶습니다.

그리고 ID가 있으면

<div class="myclass"></div>

클래스가 아닌 다른 수단을 통해 요소를 jQuery 객체로 가져온 후

var className = $('#sidebar div:eq(14)').attr('class');

트릭을해야합니다. ID의 경우 .attr('id').

요소가 래퍼가없는 순수 DOM 노드 인 이벤트 처리기 또는 기타 jQuery 메서드 내부에있는 경우 다음을 사용할 수 있습니다.

this.className // for classes, and
this.id // for IDs

둘 다 표준 DOM 메서드이며 모든 브라우저에서 잘 지원됩니다.


.hasClass()특정 요소가 있는지 확인하려는 경우 사용하는 것이 좋습니다 class. 이는 요소에 여러 class개가 있을 때 확인하기가 쉽지 않기 때문 입니다.

예:

<div id='test' class='main divhover'></div>

어디:

$('#test').attr('class');        // returns `main divhover`.

으로 .hasClass()(가) 있다면 우리는 테스트 할 수 있습니다 div클래스가 있습니다 divhover.

$('#test').hasClass('divhover'); // returns true
$('#test').hasClass('main');     // returns true

조심하세요. 아마도 당신은 클래스와 서브 클래스를 가지고있을 것입니다.

  <div id='id' class='myclass mysubclass' >dfdfdfsdfds</div>

이전 솔루션을 사용하는 경우 다음이 제공됩니다.

myclass mysubclass

따라서 클래스 선택기 를 사용하려면 다음을 수행하십시오.

var className = '.'+$('#id').attr('class').split(' ').join('.')

그리고 당신은

.myclass.mysubclass

이제 위의 div와 같은 클래스가 동일한 모든 요소를 ​​선택하려면 다음을 수행하십시오.

   var brothers=$('.'+$('#id').attr('class').split(' ').join('.'))

그것의 의미는

var brothers=$('.myclass.mysubclass')

2018 업데이트

또는 바닐라 자바 ​​스크립트로 2 줄로 구현할 수 있습니다.

  const { classList } = document.querySelector('#id');
  document.querySelectorAll(`.${Array.from(classList).join('.')}`);

이것은 한 요소를 사용하여 두 번째 클래스를 여러 클래스로 가져 오는 것입니다.

var class_name = $('#videobuttonChange').attr('class').split(' ')[1];

간단히 사용할 수 있습니다.

var className = $('#id').attr('class');


다음 <div>이있는 경우 id:

​<div id="test" class="my-custom-class"></div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

...당신은 시도 할 수 있습니다:

var yourClass = $("#test").prop("class");

이있는 경우 다음 <div>class시도 할 수 있습니다.

var yourClass = $(".my-custom-class").prop("class");

split 함수를 사용하여 클래스 이름을 추출하려는 경우 예상치 못한 결과를 생성 할 수있는 잠재적 인 형식화 변형을 보상해야합니다. 예를 들면 :

" myclass1  myclass2 ".split(' ').join(".")

생산하다

".myclass1..myclass2."

클래스 이름에 허용되는 문자 집합을 일치시키기 위해 정규식을 사용하는 것이 좋습니다. 예를 들면 :

" myclass1  myclass2  ".match(/[\d\w-_]+/g);

생산하다

["myclass1", "myclass2"]

The regular expression is probably not complete, but hopefully you understand my point. This approach mitigates the possibility of poor formatting.


To complete Whitestock answer (which is the best I found) I did :

className = $(this).attr('class').match(/[\d\w-_]+/g);
className = '.' + className.join(' .');

So for " myclass1 myclass2 " the result will be '.myclass1 .myclass2'


You can get class Name by two ways :

var className = $('.myclass').attr('class');

OR

var className = $('.myclass').prop('class');

<div id="elem" class="className"></div>

With Javascript

document.getElementById('elem').className;

With jQuery

$('#elem').attr('class');

OR

$('#elem').get(0).className;

If you do not know the class name BUT you know the ID you can try this:

<div id="currentST" class="myclass"></div>

Then Call it using :

alert($('#currentST').attr('class'));

If you want to get classes of div and then want to check if any class exists then simple use.

if ( $('#div-id' ).hasClass( 'classname' ) ) {
    // do something...
}

e.g;

if ( $('body').hasClass( 'home' ) ) {
    $('#menu-item-4').addClass('active');
}

Try it

HTML

<div class="class_area-1">
    area 1
</div>

<div class="class_area-2">
    area 2
</div>

<div class="class_area-3">
    area 3
</div>

jQuery

<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="application/javascript">
    $('div').click(function(){
        alert($(this).attr('class'));
    });
</script>

if we have single or we want first div element we can use

$('div')[0].className otherwise we need an id of that element


Best way to get class name in javascript or jquery

attr() attribute function is used to get and set attribute.


Get Class

jQuery('your selector').attr('class');  // Return class

Check class exist or not

The hasClass() method checks if any of the selected elements have a specified class name.

 if(jQuery('selector').hasClass('abc-class')){
        // Yes Exist
    }else{
        // NOt exists
    }

Set Class

jQuery('your selector').attr('class','myclass');  // It will add class to your selector

Get Class on Click of button using jQuery

jQuery(document).on('click','button',function(){
     var myclass = jQuery('#selector').attr('class');
});

Add class if selector have no any class using jQuery

if ( $('#div-id' ).hasClass( 'classname' ) ) {
        // Add your code
    }

Get the second class into multiple classes using into a element

Change array position in place of [1] to get particular class.

var mysecondclass = $('#mydiv').attr('class').split(' ')[1];

If we have a code:

<div id="myDiv" class="myClass myClass2"></div> 

to take class name by using jQuery we could define and use a simple plugin method:

$.fn.class = function(){
  return Array.prototype.slice.call( $(this)[0].classList );
}

or

 $.fn.class = function(){
   return $(this).prop('class');
 } 

The use of the method will be:

$('#myDiv').class();

We have to notice that it will return a list of classes unlike of native method element.className which returns only first class of the attached classes. Because often the element has more than one class attached to it, I recommend you not to use this native method but element.classlist or the method described above.

The first variant of it will return a list of classes as an array, the second as a string - class names separated by spaces:

// [myClass, myClass2]
// "myClass myClass2"

Another important notice is that both methods as well as jQuery method

$('div').prop('class');

return only class list of the first element caught by the jQuery object if we use a more common selector which points many other elements. In such a case we have to mark the element, we want to get his classes, by using some index, e.g.

$('div:eq(2)').prop('class');

It depends also what you need to do with these classes. If you want just to check for a class into the class list of the element with this id you should just use method "hasClass":

if($('#myDiv').hasClass('myClass')){
   // do something
}

as mentioned in the comments above. But you could need to take all classes as a selector, then use this code:

$.fn.classes = function(){
   var o = $(this);
   return o.prop('class')? [''].concat( o.prop('class').split(' ') ).join('.') : '';
 } 

 var mySelector = $('#myDiv').classes();

The result will be:

// .myClass.myClass2

and you could get it to create dynamically a specific rewriting css rule for example.

Regards


use like this:-

$(".myclass").css("color","red");

if you've used this class more than once then use each operator

$(".myclass").each(function (index, value) {
//do you code
}

참고URL : https://stackoverflow.com/questions/2400386/get-class-name-using-jquery

반응형