반응형
jQuery를 사용하여 클래스가 있는 조상이 있는지 확인합니다.
jQuery에서 부모님, 조부모님, 증조부모님 중에 수업이 있는지 확인할 수 있는 방법이 있습니까?
나는 마크업 구조를 가지고 있어서 코드에서 이런 종류의 일을 하게 되었습니다.
$(elem).parent().parent().parent().parent().hasClass('left')
하지만 코드 가독성을 위해 이런 종류의 일은 피하고 싶습니다."어떤 부모/조부모/증조부모에게도 이 수업이 있습니다"라고 말할 수 있는 방법이 있습니까?
저는 jQuery 1.7.2를 사용하고 있습니다.
if ($elem.parents('.left').length) {
}
요소 조상을 필터링하는 방법은 여러 가지가 있습니다.
if ($elem.closest('.parentClass').length /* > 0*/) {/*...*/}
if ($elem.parents('.parentClass').length /* > 0*/) {/*...*/}
if ($elem.parents().hasClass('parentClass')) {/*...*/}
if ($('.parentClass').has($elem).length /* > 0*/) {/*...*/}
if ($elem.is('.parentClass *')) {/*...*/}
조심해요.closest()
선택기를 확인하는 동안 method에 요소 자체가 포함되어 있습니다.
또는 일치하는 고유한 선택기가 있는 경우$elem
,예#myElem
사용할 수 있는 항목:
if ($('.parentClass:has(#myElem)').length /* > 0*/) {/*...*/}
if(document.querySelector('.parentClass #myElem')) {/*...*/}
스타일 지정 목적으로만 요소의 상위 클래스를 일치시키려면 CSS 규칙을 사용하십시오.
.parentClass #myElem { /* CSS property set */ }
사용할 수 있습니다.parents
지정된 메서드.class
선택하고 일치하는 항목이 있는지 확인합니다.
if ($elem.parents('.left').length != 0) {
//someone has this class
}
언급URL : https://stackoverflow.com/questions/17084839/check-if-any-ancestor-has-a-class-using-jquery
반응형
'source' 카테고리의 다른 글
ScrollView 내의 RecyclerView가 원활하게 스크롤되지 않음 (0) | 2023.08.20 |
---|---|
파워셸을 사용하여 IIS 버전 찾기 (0) | 2023.08.20 |
jQuery 객체 등식 (0) | 2023.08.20 |
Git에서 분기의 해시를 찾는 방법은 무엇입니까? (0) | 2023.08.20 |
MARIA DB 쿼리에서 환경 변수 읽기 (0) | 2023.08.20 |