JQuery 요소가 DOM에 있는지 확인하려면 어떻게 해야 합니까?
제가 어떤 요소를 정의한다고 가정해 보겠습니다.
$foo = $('#foo');
그리고 난 다음에 전화합니다.
$foo.remove()
어떤 사건으로부터.제 질문은 $foo가 DOM에서 제거되었는지 여부를 어떻게 확인할 수 있습니까?나는 그것을 발견했습니다.$foo.is(':hidden')효과가 있지만, 내가 전화만 하면 물론 그것도 사실이 될 것입니다.$foo.hide().
다음과 같이:
if (!jQuery.contains(document, $foo[0])) {
//Element is detached
}
요소의 부모 중 하나가 제거된 경우에도 이 기능은 계속 작동합니다(이 경우 요소 자체에 부모가 있음).
이렇게 하면 어떨까요?
$element.parents('html').length > 0
가장 성능이 좋은 방법은 다음과 같습니다.
document.contains(node); // boolean
이것은 jQuery에서도 작동합니다.
document.contains($element[0]); // var $element = $("#some-element")
document.contains(this[0]); // in contexts like $.each(), `this` is the jQ object
MDN에서 소스
참고:
질문을 입력하던 중에 답을 발견했습니다: 통화
$foo.parent()
한다면$f00DOM에서 제거되었습니다.$foo.parent().length === 0그렇지 않으면 길이가 1 이상이 됩니다.
[편집: 제거된 요소는 여전히 상위를 가질 수 있기 때문에 완전히 정확하지는 않습니다. 예를 들어, 제거된 요소를 제거하는 경우<ul>각각의 아이들<li>s는 여전히 부모가 있을 것입니다.대신 SLaks의 답변을 사용합니다.
제가 코멘트(너무 낮은 업보)로 답변을 드릴 수 없기 때문에, 전체 답변을 드립니다.가장 빠른 방법은 브라우저 지원을 위해 jQuery 검사를 쉽게 실행 취소하고 상수 요인을 최소화하는 것입니다.
http://jsperf.com/jquery-element-in-dom/28 에서도 볼 수 있듯이 코드는 다음과 같습니다.
var isElementInDOM = (function($) {
var docElt = document.documentElement, find,
contains = docElt.contains ?
function(elt) { return docElt.contains(elt); } :
docElt.compareDocumentPosition ?
function(elt) {
return docElt.compareDocumentPosition(elt) & 16;
} :
((find = function(elt) {
return elt && (elt == docElt || find(elt.parentNode));
}), function(elt) { return find(elt); });
return function(elt) {
return !!(elt && ((elt = elt.parent) == docElt || contains(elt)));
};
})(jQuery);
이것은 의미론적으로 jQuery.contains(document.documentElement, elt[0])와 같습니다.
부모를 반복하는 대신 요소가 돔에서 분리될 때 모두 0인 경계 직선을 얻을 수 있습니다.
function isInDOM(element) {
var rect=element.getBoundingClientRect();
return (rect.top || rect.bottom || rect.height || rect.width)?true:false;
}
상단과 왼쪽이 제로인 제로 폭과 높이 요소의 가장자리 케이스를 처리하려면 문서까지 부모를 반복하여 이중 확인할 수 있습니다.몸
저는 이 방법이 마음에 들었습니다.jQuery 및 DOM 검색이 없습니다.먼저 상위 부모(조상)를 찾습니다.그런 다음 그것이 documentElement인지 확인합니다.
function ancestor(HTMLobj){
while(HTMLobj.parentElement){HTMLobj=HTMLobj.parentElement}
return HTMLobj;
}
function inTheDOM(obj){
return ancestor(obj)===document.documentElement;
}
페로의 의견에 동의합니다.또한 다음과 같이 수행할 수 있습니다.
$foo.parents().last().is(document.documentElement);
jQuery.fn.isInDOM = function () {
if (this.length == 1) {
var element = this.get(0);
var rect = element.getBoundingClientRect();
if (rect.top + rect.bottom + rect.width + rect.height + rect.left + rect.right == 0)
return false;
return true;
}
return false;
};
왜 그냥:if( $('#foo').length === 0)...?
if($foo.nodeType ){ element is node type}
언급URL : https://stackoverflow.com/questions/3086068/how-do-i-check-whether-a-jquery-element-is-in-the-dom
'programing' 카테고리의 다른 글
| iOS 애플리케이션 스플래시 화면에 사용되는 크기는 무엇입니까? (0) | 2023.08.23 |
|---|---|
| 신속하고 돌연변이적인 구조 (0) | 2023.08.23 |
| Spring @ContextXml에 적합한 위치를 지정하는 방법 (0) | 2023.08.23 |
| 명령이 성공적으로 실행되었는지 확인합니다. (0) | 2023.08.23 |
| 팬더와 함께 Excel XML .xls 파일 읽기 (0) | 2023.08.23 |