[javascript] jQuery : 특정 클래스 이름의 div가 있는지 확인하십시오.

jQuery를 사용하여 프로그래밍 방식으로 div다음과 같은 여러 가지를 생성하고 있습니다 .

<div class="mydivclass" id="myid1">Some Text1</div>
<div class="mydivclass" id="myid2">Some Text2</div>

내 코드 어딘가에 이러한 DIV가 있는지 감지해야합니다. div의 클래스 이름은 동일하지만 각 div마다 ID가 변경됩니다. jQuery를 사용하여 감지하는 방법에 대한 아이디어가 있습니까?



답변

JQuery에서 반환 된 첫 번째 객체를 확인하여이를 단순화 할 수 있습니다.

if ($(".mydivclass")[0]){
    // Do something if class exists
} else {
    // Do something if class does not exist
}

이 경우 첫 번째 ( [0]) 색인에 값이 참 이면 클래스가 있다고 가정하십시오.

편집 2013년 4월 10일 : 나는 jsperf 테스트 케이스를 만들었습니다 여기에 .


답변

을 사용할 수 size()있지만 jQuery는 다른 함수 호출의 오버 헤드를 피하기 위해 길이를 사용하는 것이 좋습니다.

$('div.mydivclass').length

그래서:

// since length is zero, it evaluates to false
if ($('div.mydivclass').length) {

http://api.jquery.com/size/

http://api.jquery.com/length/

최신 정보

선택된 답변은 perf 테스트를 사용하지만 perf의 일부로 요소 선택도 포함되어 있기 때문에 약간의 결함이 있습니다. 여기서는 테스트되지 않습니다. 업데이트 된 성능 테스트는 다음과 같습니다.

http://jsperf.com/check-if-div-exists/3

테스트의 첫 번째 실행은 속성 검색이 인덱스 검색보다 빠르다는 것을 보여 주지만 IMO는 무시할 만합니다. 나는 여전히 길이를 사용하는 것이 더 간결한 조건 대신 코드의 의도에 대해 더 의미가 있습니다.


답변

jQuery없이 :

기본 JavaScript는 항상 더 빠릅니다. 이 경우 : (예)

if (document.querySelector('.mydivclass') !== null) {
    // .. it exists
}

부모 요소에 특정 클래스의 다른 요소가 포함되어 있는지 확인하려면 다음 중 하나를 사용할 수 있습니다. (예)

var parent = document.querySelector('.parent');

if (parent.querySelector('.child') !== null) {
    // .. it exists as a child
}

또는 .contains()부모 요소 에서 메서드를 사용할 수 있습니다 . (예)

var parent = document.querySelector('.parent'),
    child = document.querySelector('.child');

if (parent.contains(child)) {
    // .. it exists as a child
}

마지막으로 주어진 요소에 특정 클래스 만 포함되어 있는지 확인하려면 다음을 사용하십시오.

if (el.classList.contains(className)) {
    // .. el contains the class
}


답변

$('div').hasClass('mydivclass')// Returns true if the class exist.


답변

Jquery를 사용하지 않는 솔루션은 다음과 같습니다.

var hasClass = element.classList.contains('class name to search');
// hasClass is boolean
if(hasClass === true)
{
     // Class exists
}

참조 링크


답변

아주 간단합니다 …

if ($('.mydivclass').length > 0) {
  //do something
}


답변

div요소를 명시 적으로 테스트하려면 다음을 수행하십시오 .

if( $('div.mydivclass').length ){...}