한 요소가 다른 요소에 포함되어 있는지 Javascript를 확인하는 방법
한 DOM 요소가 다른 DOM 요소의 자식인지 어떻게 확인할 수 있습니까? 이를위한 내장 된 방법이 있습니까? 예를 들면 다음과 같습니다.
if (element1.hasDescendant(element2))
또는
if (element2.hasParent(element1))
그렇지 않으면 어떤 아이디어가 이것을 수행 하는가? 또한 크로스 브라우저 여야합니다. 또한 자녀가 부모 아래에 여러 수준으로 중첩 될 수 있다고 언급해야합니다.
parentNode
속성을 사용하면 작동합니다. 또한 크로스 브라우저 관점에서 보면 매우 안전합니다. 관계가 한 수준으로 알려진 경우 간단히 확인할 수 있습니다.
if (element2.parentNode == element1) { ... }
자식이 부모 내부에 임의로 중첩 될 수있는 경우 다음과 유사한 함수를 사용하여 관계를 테스트 할 수 있습니다.
function isDescendant(parent, child) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
}
Node.contains
이제는 표준이며 모든 브라우저에서 사용할 수 있으므로을 사용해야 합니다.
https://developer.mozilla.org/en-US/docs/Web/API/Node.contains
방금 '광산'을 공유해야했습니다.
개념적으로 Asaph의 답변 과 동일하지만 (동일한 브라우저 간 호환성, 심지어 IE6에서도 이점이 있음) 크기가 훨씬 작거나 크기가 자주 필요하지 않을 때 유용합니다.
function childOf(/*child node*/c, /*parent node*/p){ //returns boolean
while((c=c.parentNode)&&c!==p);
return !!c;
}
.. 또는 한 줄짜리 문자 ( 64 문자 만 !) :
function childOf(c,p){while((c=c.parentNode)&&c!==p);return !!c}
그리고 여기에 jsfiddle .
사용법 :
childOf(child, parent)
부울true
| false
.
설명 :
while
while 조건이로 평가되는 한 평가합니다true
. (AND) 연산자 반환이 부울 참 / 거짓을 된 후 왼쪽과 오른쪽을 평가할 만 한다면 좌측이 사실 ( ) .&&
left-hand && right-hand
(의 &&
) 의 왼쪽 은 다음과 같습니다 (c=c.parentNode)
.
먼저 parentNode
of c
를 할당 c
한 다음 AND 연산자가 결과 c
를 부울로 평가합니다 .
이후 parentNode
반환 null
부모 왼쪽이없는 경우 null
로 변환되어 false
더 이상 부모가 없을 때 잠시 루프가 제대로 중지됩니다.
(의 &&
) 의 오른쪽 은 다음과 같습니다 c!==p
. 비교 연산자 '이다 하지 정확히 동일한'. 따라서 자녀의 부모가 부모 (지정한)가 아니면로 평가 되지만 자녀의 부모 가 부모이면 평가됩니다 . 그래서 경우 FALSE로는, 그 조작 복귀 그동안 조건과 같은 동안 루프는 정지한다. (몸통이 필요 없으며 닫는 세미콜론이 필요합니다.)!==
true
false
c!==p
&&
false
;
따라서 while 루프가 끝날 때 부모를 찾았을 때 c
노드가 아니고 노드가 아닌 (루프가 일치하지 않고 끝까지 갔을 때)null
null
따라서 단순히 우리 return
와 (노드 대신, 부울 값 환산) 사실 : return !!c;
다음 !
( NOT
오퍼레이터)은 부울 값 (반전 true
된다 false
반대로). 해당 값을 반전시키기 전에 (노드 또는 널)을 부울
!c
로 변환 c
합니다. 따라서 두 번째 !
( !!c
)를 추가하면 이 false가 다시 true !!
로 변환됩니다. 따라서 double 은 종종 '무언가로 변환'하는 데 사용됩니다.
추가 :
기능의 몸 / 페이로드는 너무 작아서,이 경우에 따라 하나가 (이 자주 사용하고 코드에 한 번만 표시되지 않은 경우 등) 수있는 기능 (포장)를 생략하고 바로 동안 루프를 사용하는 경우에도 :
var a=document.getElementById('child'),
b=document.getElementById('parent'),
c;
c=a; while((c=c.parentNode)&&c!==b); //c=!!c;
if(!!c){ //`if(c)` if `c=!!c;` was used after while-loop above
//do stuff
}
대신에:
var a=document.getElementById('child'),
b=document.getElementById('parent'),
c;
function childOf(c,p){while((c=c.parentNode)&&c!==p);return !!c}
c=childOf(a, b);
if(c){
//do stuff
}
언급되지 않은 또 다른 솔루션 :
var parent = document.querySelector('.parent');
if (parent.querySelector('.child') !== null) {
// .. it's a child
}
It doesn't matter whether the element is a direct child, it will work at any depth.
Alternatively, using the .contains()
method:
var parent = document.querySelector('.parent'),
child = document.querySelector('.child');
if (parent.contains(child)) {
// .. it's a child
}
Take a look at Node#compareDocumentPosition.
function isDescendant(ancestor,descendant){
return ancestor.compareDocumentPosition(descendant) &
Node.DOCUMENT_POSITION_CONTAINS;
}
function isAncestor(descendant,ancestor){
return descendant.compareDocumentPosition(ancestor) &
Node.DOCUMENT_POSITION_CONTAINED_BY;
}
Other relationships include DOCUMENT_POSITION_DISCONNECTED
, DOCUMENT_POSITION_PRECEDING
, and DOCUMENT_POSITION_FOLLOWING
.
Not supported in IE<=8.
You can use the contains method
var result = parent.contains(child);
or you can try to use compareDocumentPosition()
var result = nodeA.compareDocumentPosition(nodeB);
The last one is more powerful: it return a bitmask as result.
I came across a wonderful piece of code to check whether or not an element is a child of another element. I have to use this because IE doesn't support the .contains
element method. Hope this will help others as well.
Below is the function:
function isChildOf(childObject, containerObject) {
var returnValue = false;
var currentObject;
if (typeof containerObject === 'string') {
containerObject = document.getElementById(containerObject);
}
if (typeof childObject === 'string') {
childObject = document.getElementById(childObject);
}
currentObject = childObject.parentNode;
while (currentObject !== undefined) {
if (currentObject === document.body) {
break;
}
if (currentObject.id == containerObject.id) {
returnValue = true;
break;
}
// Move up the hierarchy
currentObject = currentObject.parentNode;
}
return returnValue;
}
try this one:
x = document.getElementById("td35");
if (x.childElementCount > 0) {
x = document.getElementById("LastRow");
x.style.display = "block";
}
else {
x = document.getElementById("LastRow");
x.style.display = "none";
}
I recently came across this function which might do:
'Programming' 카테고리의 다른 글
cocoapods 버전 1.0.0.beta.1에서 포드 설치 표시 오류 (0) | 2020.05.21 |
---|---|
Docker에서 디렉토리 변경 명령? (0) | 2020.05.21 |
자바에서 소수점 이하 2 자리까지 반올림? (0) | 2020.05.21 |
테이블의 기본 데이터 정렬을 변경하는 방법은 무엇입니까? (0) | 2020.05.21 |
styles.xml에서 'Theme'기호를 확인할 수 없습니다 (Android Studio) (0) | 2020.05.21 |