보이는 DOM에 요소가 있는지 확인하는 방법?
방법을 사용하지 않고 요소가 존재하는지 어떻게 테스트 getElementById
합니까? 참조 용 라이브 데모 를 설정했습니다 . 또한 여기에 코드를 인쇄합니다.
<!DOCTYPE html>
<html>
<head>
<script>
var getRandomID = function (size) {
var str = "",
i = 0,
chars = "0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ";
while (i < size) {
str += chars.substr(Math.floor(Math.random() * 62), 1);
i++;
}
return str;
},
isNull = function (element) {
var randomID = getRandomID(12),
savedID = (element.id)? element.id : null;
element.id = randomID;
var foundElm = document.getElementById(randomID);
element.removeAttribute('id');
if (savedID !== null) {
element.id = savedID;
}
return (foundElm) ? false : true;
};
window.onload = function () {
var image = document.getElementById("demo");
console.log('undefined', (typeof image === 'undefined') ? true : false); // false
console.log('null', (image === null) ? true : false); // false
console.log('find-by-id', isNull(image)); // false
image.parentNode.removeChild(image);
console.log('undefined', (typeof image === 'undefined') ? true : false); // false ~ should be true?
console.log('null', (image === null) ? true : false); // false ~ should be true?
console.log('find-by-id', isNull(image)); // true ~ correct but there must be a better way than this?
};
</script>
</head>
<body>
<div id="demo"></div>
</body>
</html>
기본적으로 위의 코드가 보여주는 것은 변수에 저장된 다음 dom에서 제거되는 요소입니다. 요소가 돔에서 제거되었지만 변수는 처음 선언되었을 때와 같이 요소를 유지합니다. 즉, 요소 자체에 대한 실시간 참조가 아니라 복제본입니다. 결과적으로 변수의 값 (요소)이 존재하는지 확인하면 예기치 않은 결과가 제공됩니다.
이 isNull
함수는 변수에서 요소 존재를 확인하려는 시도이며 작동하지만 동일한 결과를 얻는 더 쉬운 방법이 있는지 알고 싶습니다.
추신 : 주제와 관련된 좋은 기사를 알고 있다면 JavaScript 변수가 왜 이런 식으로 작동하는지 관심이 있습니다.
일부 사람들이 여기에 착륙하는 것 같으며 요소 가 존재 하는지 알고 싶어 합니다 (원래 질문과 조금 다릅니다).
브라우저의 선택 방법 중 하나를 사용하여 진실한 값 (일반적으로)을 확인하는 것만 큼 간단 합니다.
내 요소가 있었다 예를 들어, id
의를 "find-me"
, 나는 간단하게 사용할 수 ...
var elementExists = document.getElementById("find-me");
이것은 요소 또는에 대한 참조를 반환하도록 지정되어 있습니다 null
. 부울 값이 있어야하는 경우 !!
메서드 호출 전에 a를 던지기 만하면 됩니다.
또한 (all living off document
) 와 같은 요소를 찾기 위해 존재하는 다른 많은 방법 중 일부를 사용할 수 있습니다 .
querySelector()
/querySelectorAll()
getElementsByClassName()
getElementsByName()
이러한 메소드 중 일부는을 반환 하므로 a 는 객체이므로 진실 이므로 속성 NodeList
을 확인하십시오 .length
NodeList
Csuwldcat은 요소가 가시적 인 DOM의 일부로 존재하는지 (원래 질문 한 것과 같이) 실제로 결정하기 위해 (이 답변에 포함 된 것처럼) 자신을 굴리는 것보다 더 나은 솔루션을 제공합니다 . 즉, contains()
DOM 요소 에서 메소드 를 사용합니다 .
당신은 그렇게 사용할 수 있습니다 ...
document.body.contains(someReferenceToADomElement);
getElementById()
가능한 경우 왜 사용하지 않겠습니까?
또한 jQuery를 사용하여 쉽게 수행 할 수있는 방법이 있습니다.
if ($('#elementId').length > 0) {
// exists.
}
그리고 타사 라이브러리를 사용할 수 없다면 기본 JavaScript를 고수하십시오.
var element = document.getElementById('elementId');
if (typeof(element) != 'undefined' && element != null)
{
// exists.
}
Node.contains DOM API를 사용하면 페이지 (현재 DOM에 있음)의 요소가 있는지 쉽게 확인할 수 있습니다.
document.body.contains(YOUR_ELEMENT_HERE);
CROSS-BROWSER 참고 : document
IE 의 객체에는 contains()
방법 이 없습니다 -브라우저 간 호환성을 보장하려면 document.body.contains()
대신 사용하십시오
나는 단순히 :
if(document.getElementById("myElementId")){
alert("Element exists");
} else {
alert("Element does not exist");
}
나를 위해 일하고 아직 아무런 문제가 없었습니다 ....
에서 모질라 개발자 네트워크
이 함수는 요소가 페이지 본문에 있는지 확인합니다. contains가 포함되어 있고 본문에 자체가 포함되어 있는지 확인하는 것이 isInPage의 의도가 아닌 경우이 경우 명시 적으로 false를 반환합니다.
function isInPage(node) {
return (node === document.body) ? false : document.body.contains(node);
}
node 는에서 확인하려는 노드 입니다.
parentNode 속성이 null인지 확인할 수 있습니까?
즉
if(!myElement.parentNode)
{
//node is NOT on the dom
}
else
{
//element is on the dom
}
가장 쉬운 해결책은 baseURI 속성 을 확인하는 것 입니다.이 속성은 요소가 DOM에 삽입 될 때만 설정되고 제거 될 때 빈 문자열로 되돌아갑니다.
var div = document.querySelector('div');
// "div" is in the DOM, so should print a string
console.log(div.baseURI);
// Remove "div" from the DOM
document.body.removeChild(div);
// Should print an empty string
console.log(div.baseURI);
<div></div>
jQuery 솔루션 :
if ($('#elementId').length) {
// element exists, do something...
}
이것은 jQuery를 사용하여 저에게 효과적이며 사용하지 않아도 $('#elementId')[0]
됩니다.
csuwldcat의 솔루션 은 가장 좋은 것으로 보이지만 iframe과 같이 자바 스크립트가 실행되는 것과 다른 문서에있는 요소에서 올바르게 작동하려면 약간 수정해야합니다.
YOUR_ELEMENT.ownerDocument.body.contains(YOUR_ELEMENT);
ownerDocument
일반 ol ' document
(요소의 소유자 문서를 참조하거나 참조하지 않을 수 있음) 와 달리 요소의 속성 사용에 유의 하십시오.
torazaburo는 로컬이 아닌 요소에서도 작동 하는 더 간단한 방법 을 게시 했지만 불행히도 baseURI
현재 브라우저에서 균일하게 구현되지 않은 속성을 사용합니다 (웹킷 기반에서만 작동 할 수 있음). 비슷한 방식으로 사용할 수있는 다른 요소 또는 노드 속성을 찾을 수 없었으므로 위의 해결책 인 한 그 동안 얻을 수있는만큼 좋습니다.
jQuery의 한 줄 코드를 통해 요소가 있는지 확인하는 간단한 방법을 수행 할 수 있습니다.
아래 코드는 다음과 같습니다.
if ($('#elementId').length > 0) {
// do stuff here if element exists
}else {
// do stuff here if element not exists
}
다른 옵션 element.closest :
element.closest('body') === null
jQuery를 사용한 간단한 솔루션
$('body').find(yourElement)[0] != null
jQuery.contains
요소가 다른 요소의 자손인지 확인하는을 사용할 수도 있습니다 . document
DOM 페이지에 존재하는 요소가의 자손이므로 검색하기 위해 부모 요소로 전달되었습니다 document
.
jQuery.contains( document, YOUR_ELEMENT)
부모를 반복하는 대신 요소가 dom에서 분리 될 때 경계 0을 얻을 수 있습니다.
function isInDOM(element) {
if (!element) return false;
var rect=element.getBoundingClientRect();
return (rect.top || rect.left || rect.height || rect.width)?true:false;
}
너비가 0 인 요소와 너비가 0 인 요소의 가장자리를 0에서 왼쪽으로 처리하려면 문서까지 부모를 반복하여 두 번 확인할 수 있습니다.
function isInDOM(element) {
if (!element) return false;
var rect=element.getBoundingClientRect();
if (element.top || element.left || element.height || element.width) return true;
while(element) {
if (element==document.body) return true;
element=element.parentNode;
}
return false;
}
// this will work prefect in all :D
function basedInDocument(el) {
// this function use for checking if this element in a real DOM
while (el.parentElement != null) {
if (el.parentElement == document.body) {
return true;
}
el = el.parentElement; // for check parent of
} // if loop break will return false mean element not in real DOM
return false;
}
나는이 접근법을 좋아했다
var elem = document.getElementById('elementID');
if( elem )do this
else
do that
또한
var elem = ((document.getElementById('elemID')) ? true:false);
if( elem ) do this
else
do that
이것을 사용하십시오 :
var isInDOM = function(element, inBody) {
var _ = element, last;
while (_) {
last = _;
if (inBody && last === document.body) { break;}
_ = _.parentNode;
}
return inBody ? last === document.body : last === document;
};
querySelectorAll
함께 사용 forEach
:
document.querySelectorAll('.my-element').forEach((element) => {
element.classList.add('new-class');
});
반대로 :
const myElement = document.querySelector('.my-element');
if (myElement) {
element.classList.add('new-class');
}
이것을 시도하십시오, 이것은 가장 안정적인 해결책입니다.
window.getComputedStyle(x).display == ""
즉 :
var x = document.createElement("html")
var y = document.createElement("body")
var z = document.createElement("div")
x.appendChild(y);
y.appendChild(z);
z.style.display = "block";
console.log(z.closest("html") == null);//false
console.log(z.style.display);//block
console.log(window.getComputedStyle(z).display == "");//true
요소가 <html>
via 의 자식인지 확인하십시오 Node::contains()
.
const div = document.createElement('div');
document.documentElement.contains(div); //-> false
document.body.appendChild(div);
document.documentElement.contains(div); //-> true
나는 이것을 is-dom-detached 에서 다루었 다 .
HTML 요소를 제외한 모든 기존 요소에는 parentElement가 설정되어 있습니다!
function elExists (e) {
return (e.nodeName === 'HTML' || e.parentElement !== null);
};
참고 URL : https://stackoverflow.com/questions/5629684/how-to-check-if-element-exists-in-the-visible-dom
'Programming' 카테고리의 다른 글
핍의 캐시를 제거 하시겠습니까? (0) | 2020.02.27 |
---|---|
파이썬 모듈에서 모든 함수를 나열하는 방법? (0) | 2020.02.27 |
PowerShell에서 문자열이 null인지 또는 비어 있는지 어떻게 확인할 수 있습니까? (0) | 2020.02.27 |
iOS 및 WatchKit에서 이미지 tintColor를 변경하는 방법 (0) | 2020.02.27 |
iPhone / iPad / IO를위한 빠르고 마른 PDF 뷰어-팁과 힌트? (0) | 2020.02.27 |