플레인 JavaScript에서 "hasClass" 함수는 무엇입니까?
jQuery's는 어떻게 하죠?hasClass플레인 ol' JavaScript를 사용할 수 있습니까?예를들면,
<body class="foo thatClass bar">
JavaScript는 어떻게 질문합니까?<body>가지다thatClass?
간단하게 사용classList.contains():
if (document.body.classList.contains('thatClass')) {
// do some stuff
}
기타 용도classList:
document.body.classList.add('thisClass');
// $('body').addClass('thisClass');
document.body.classList.remove('thatClass');
// $('body').removeClass('thatClass');
document.body.classList.toggle('anotherClass');
// $('body').toggleClass('anotherClass');
브라우저 지원:
- 크롬 8.0
- 파이어폭스 3.6
- IE 10
- 오페라 11.50
- Safari 5.1
확인하실 수 있습니다.element.className일치하다/\bthatClass\b/.
\b단어 구분과 일치합니다.
또는 jQuery 자체 구현을 사용할 수 있습니다.
var className = " " + selector + " ";
if ( (" " + element.className + " ").replace(/[\n\t]/g, " ").indexOf(" thatClass ") > -1 )
일반적인 질문에 답하려면 github에 있는 jQuery의 소스 코드 또는 특히 이 소스 뷰어에 있는 소스를 참조하십시오.
가장 효과적인 라이너는
- (Obling의 응답과 달리) 부울을 반환합니다.
- 검색할 때 false positive를 반환하지 않습니다.
thisClass가지고 있는 요소에서class="thisClass-suffix". - 는 IE6 이상의 모든 브라우저와 호환성이 있습니다.
function hasClass( target, className ) {
return new RegExp('(\\s|^)' + className + '(\\s|$)').test(target.className);
}
// 1. Use if for see that classes:
if (document.querySelector(".section-name").classList.contains("section-filter")) {
alert("Grid section");
// code...
}
<!--2. Add a class in the .html:-->
<div class="section-name section-filter">...</div>
사용 중인 클래스를 저장하는 속성은 다음과 같습니다.className.
다음과 같이 말할 수 있습니다.
if (document.body.className.match(/\bmyclass\b/)) {
....
}
jQuery가 어떻게 모든 것을 수행하는지 보여주는 위치를 원한다면 다음을 제안합니다.
http://code.jquery.com/jquery-1.5.js
Element.matches()
대신$(element).hasClass('example')jQuery에서는 다음과 같이 사용할 수 있습니다.element.matches('.example')플레인 JavaScript:
if (element.matches('.example')) {
// Element has example class ...
}
hasClass 함수:
HTMLElement.prototype.hasClass = function(cls) {
var i;
var classes = this.className.split(" ");
for(i = 0; i < classes.length; i++) {
if(classes[i] == cls) {
return true;
}
}
return false;
};
addClass 함수:
HTMLElement.prototype.addClass = function(add) {
if (!this.hasClass(add)){
this.className = (this.className + " " + add).trim();
}
};
removeClass 함수:
HTMLElement.prototype.removeClass = function(remove) {
var newClassName = "";
var i;
var classes = this.className.replace(/\s{2,}/g, ' ').split(" ");
for(i = 0; i < classes.length; i++) {
if(classes[i] !== remove) {
newClassName += classes[i] + " ";
}
}
this.className = newClassName.trim();
};
간단한/최소한의 솔루션, 한 줄의 크로스 브라우저를 사용하며 레거시 브라우저에서도 작동합니다.
/\bmyClass/.test(document.body.className) // notice the \b command for whole word 'myClass'
이 방법은 폴리필이 필요없고 만약 당신이 그것들을 사용한다면 매우 좋다.classList퍼포먼스 면에서는 훨씬 낫습니다.적어도 나는.
업데이트: 현재 사용하고 있는 만능 솔루션인 작은 폴리필을 만들었습니다.
function hasClass(element,testClass){
if ('classList' in element) { return element.classList.contains(testClass);
} else { return new Regexp(testClass).exec(element.className); } // this is better
//} else { return el.className.indexOf(testClass) != -1; } // this is faster but requires indexOf() polyfill
return false;
}
다른 클래스 조작에 대해서는, 여기를 참조해 주세요.
classList 및 contains를 사용하는 것이 좋습니다.
이렇게 했어요.
... for ( var i = 0; i < container.length; i++ ) {
if ( container[i].classList.contains('half_width') ) { ...
그래서 당신은 당신의 요소가 필요하고 수업 목록을 확인합니다.검색한 클래스 중 하나가 동일한 경우 true를 반환하고 그렇지 않으면 false를 반환합니다.
다음과 같은 사용:
Array.prototype.indexOf.call(myHTMLSelector.classList, 'the-class');
if (document.body.className.split(/\s+/).indexOf("thatClass") !== -1) {
// has "thatClass"
}
이 'hasClass' 기능은 IE8+, FireFox 및 Chrome에서 작동합니다.
hasClass = function(el, cls) {
var regexp = new RegExp('(\\s|^)' + cls + '(\\s|$)'),
target = (typeof el.className === 'undefined') ? window.event.srcElement : el;
return target.className.match(regexp);
}
[2021년 1월 갱신]더 좋은 방법:
hasClass = (el, cls) => {
[...el.classList].includes(cls); //cls without dot
};
위의 답변은 모두 괜찮지만, 여기 제가 간단히 생각해 낸 기능이 있습니다.그것은 꽤 잘 작동한다.
function hasClass(el, cn){
var classes = el.classList;
for(var j = 0; j < classes.length; j++){
if(classes[j] == cn){
return true;
}
}
}
이 접근법에 대해 어떻게 생각하십니까?
<body class="thatClass anotherClass"> </body>
var bodyClasses = document.querySelector('body').className;
var myClass = new RegExp("thatClass");
var trueOrFalse = myClass.test( bodyClasses );
https://jsfiddle.net/5sv30bhe/
언급URL : https://stackoverflow.com/questions/5085567/what-is-the-hasclass-function-with-plain-javascript
'source' 카테고리의 다른 글
| MySQL 데이터베이스를 SQL Server로 가져오기 (0) | 2022.11.12 |
|---|---|
| Vue JS Vuetify $emit이 처음 작동하지 않습니다. (0) | 2022.11.12 |
| CSV를 디스크에 저장하지 않고 CSV 형식의 데이터를 메모리에서 데이터베이스로 전송하려면 어떻게 해야 합니까? (0) | 2022.11.12 |
| UnicodeEncodeError: 'charmap' 코덱은 문자를 인코딩할 수 없습니다. (0) | 2022.11.12 |
| PHP의 동적 클래스 메서드 호출 (0) | 2022.11.12 |