developer tip

요소가 다른 요소의 하위 요소인지 확인하는 가장 좋은 방법

optionbox 2020. 11. 19. 08:06
반응형

요소가 다른 요소의 하위 요소인지 확인하는 가장 좋은 방법


나는 jQuery를 구현하고 내 코드베이스에서 Prototype 라이브러리를 꺼내는 과정에 있으며 jQuery에서이 기능을 구현하는 가장 좋은 방법을 제공 할 수 있는지 궁금합니다. 나는 jQuery 조상 >하위 구문에 익숙 하지만 아래 코드와 같이 요소가 거짓의 참으로 하위 요소인지 확인하고 싶습니다. 누군가 나에게 가장 효율적인 jQuery 솔루션을 줄 수 있습니까?

<div id="australopithecus">
  <div id="homo-herectus">
    <div id="homo-sapiens"></div>
  </div>
</div>

$('homo-sapiens').descendantOf('australopithecus');
// -> true

$('homo-herectus').descendantOf('homo-sapiens');
// -> false

여기서 반환 된 길이와 함께 CSS 스타일 선택을 활용할 수 있다고 생각합니다.

$('#australopithecus #homo-sapiens').length // Should be 1
$('#homo-sapiens #homo-herectus').length // Should be 0

정확히 참 / 거짓은 아니지만 0/1을 부울로 확인하면 작동합니다. :)

또는 $ ( '# parent'). find ( '# child')와 같은 작업을 수행하고 거기에서 길이를 확인할 수 있습니다.


jQuery 1.6에서는 일반적으로 다음 코드를 사용할 수 있습니다. 예를 들어 targetElt 및 parentElt는 모두 DOM 요소 또는 jQuery로 래핑 된 객체 일 수 있으며 선택 기일 수 있습니다.

$(targetElt).closest(parentElt).length > 0

다른 답변 중 일부는 ID로 요소를 참조하도록 요구하는데, ID가없는 DOM 요소 만 있으면 유용하지 않습니다. 또한 targetElt가 parentElt의 엄격한 하위 항목인지 확인하려면 (즉, parentElt를 자체 하위 항목으로 계산하지 않음)를 targetElt != parentElt호출하기 전에 확인을 추가 .closest()하거나 다음 .parents().find()과 같이 사용하십시오 . Jonathan Sampson이 제안합니다.


JQuery

jQuery> = 1.4 (2010)를 사용하면 매우 빠른 함수 jQuery.contains ()를 사용할 수 있습니다.

이 정적 메서드는 jQuery 요소 및 반환 true또는 false.

jQuery.contains( container, descendant )

예 : 요소가 문서에 있는지 확인하려면 다음을 수행 할 수 있습니다.

jQuery.contains( document.body, myElement )

네이티브 DOM

ie5 + 이후 모든 브라우저에서 지원 하는 기본 DOM 메서드 Node.contains ()도 있습니다. 따라서 jQuery 없이도 할 수 있습니다.

document.body.contains( myElement )

어때


$("#homo-herectus").parents().is("#australopithecus");

다음 is()과 같이 함수 를 사용할 수 있습니다 .

alert($('#homo-sapiens').is('#australopithecus *'));
// -> true

alert($('#homo-herectus').is('#homo-sapiens *'));
// -> false

$.fn.descendantOf = function(element) {
    element = $(element)[0];
    var current = this;
    var body    = document.body;
    while (current && current != element && current != document.body) {
        current = $(current).parent()[0];
    }
    if (typeof(current) == "undefined" || typeof(current) == "null") {
        return false;
    } else if (current == element) {
        return true;
    } else if (current == document.body) {
        return false;
    }
}

예:

<div id="foo">
    <div id="bar">
        <div id="baz"></div>
    </div>
</div>

과:

$('#foo').descendantOf('#bar');  // false
$('#foo').descendantOf('#foo');  // false
$('#foo').descendantOf(document.body);  // true
$('#bar').descendantOf('#foo');  // true
$('#baz').descendantOf('#foo');  // true

.find()Elements에서 시도 할 수 있습니다..children()

$("#lucy").find("#homo-erectus").length;

또는 반대 방향 :

$("#homo-erectus").parents().find("#lucy").length;

내가 찾은 최고의 방법은 Dan G. Switzer, II의 방법을 사용하는 것입니다. http://blog.pengoworks.com/index.cfm/2008/9/24/Using-jQuery-to-determine-if-an-element -is-a-child-of-another-element

jQuery.fn.isChildOf = function(b){ 
    return (this.parents(b).length > 0); 
};

그런 다음 플러그인을 다음과 같이 사용합니다.

$('homo-sapiens').isChildOf('australopithecus');
// -> true

$('homo-herectus').isChildOf('homo-sapiens');
// -> false

(거의) 동일한 트래버스 원칙을 사용하고 요소 자체를 포함하지 않는 가장 가까운 ()의 대안 : child.parentsUntil(ancestor).last().parent().is(ancestor).

var child = $('#homo-sapiens');
var ancestor = $('#australopithecus');

console.log(child.parentsUntil(ancestor).last().parent().is(ancestor)); // true

function descendantOf(parentId, childId) {
   return ( $('#'+parentId+' > #'+childId).length === 1 );
}

작동합니다.

As was pointed out in the comment below, if you don't want it to be just direct descendants:

function descendantOf(parentId, childId) {
   return ( $('#'+childId, $('#'+parentId)).length === 1 );
}

Supposing to rewrite your initial statement in:

$('#homo-sapiens').descendantOf('#australopithecus');

try to plugin:

(function($) {
    $.fn.descendantOf = function(parentId) {
        return this.closest(parentId).length != 0;
    }
})(jQuery)

참고URL : https://stackoverflow.com/questions/1059459/best-way-to-find-out-if-element-is-a-descendant-of-another

반응형