programing

표시 가능한 DOM에 요소가 존재하는지 확인하려면 어떻게 해야 합니까?

prostudy 2022. 9. 11. 15:32
반응형

표시 가능한 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에서 삭제되는 요소를 나타냅니다.요소가 DOM에서 제거되어도 변수는 처음 선언되었을 때와 같은 요소를 유지합니다.즉, 요소 자체에 대한 실제 참조가 아니라 복제본입니다.그 결과 변수의 값(요소)이 존재하는지 확인하면 예기치 않은 결과가 나타납니다.

isNullfunction은 변수에서 요소가 존재하는지 확인하는 것으로 동작합니다만, 같은 결과를 얻을 수 있는 보다 쉬운 방법이 있는지 알고 싶습니다.

PS: JavaScript 변수가 왜 이 주제에 관한 좋은 기사를 알고 있는지도 궁금합니다.

여기 도착해서 요소가 존재하는지 알고 싶은 사람도 있는 것 같습니다(원래 질문과는 조금 다릅니다).

이것은 브라우저의 선택 방법 중 하나를 사용하여 값(일반적으로)을 확인하는 것만으로 간단합니다.

를 들어,에는 '만', '만', '만', '만', '만',id"find-me"난그...

var elementExists = document.getElementById("find-me");

는 엘리먼트에 하기 위해 " " " " 입니다.null에는'부울값'을!!메서드 호출 전에.

) 다른 하여 요소를 수 . (모두 먹고사는 경우)document

  • querySelector()/querySelectorAll()
  • getElementsByClassName()
  • getElementsByName()

중 는 ""를 반환합니다.NodeList 꼭 해 보세요.length "", ""이기 입니다.NodeList물체이기 때문에 진부합니다.


가시적인 DOM일부로서 요소가 존재하는지 아닌지를 실제로 판별하기 위해서(원래의 질문 등), Csuldcat 는, 독자적인 것을 롤 하는 것보다 뛰어난 솔루션을 제공합니다(이 답변에 포함).즉, 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);

크로스 브라우저 주의:document Explorer가 .contains()method - 호환성을 하려면 , 「-」를 합니다.document.body.contains()★★★★★★ 。

간단하게 할 수 있는 일:

if(document.getElementById("myElementId")){
    alert("Element exists");
} else {
    alert("Element does not exist");
}

그것은 나에게 효과가 있고 아직 아무런 문제가 없었다.

사용하는 것이 좋습니다.node.isConnectedproperty(MDN 방문).

주의: 요소가 ShadowRoot에도 추가되면 true가 반환됩니다.이것은 모든 사람이 원하는 동작이 아닐 수 있습니다.

예제:

const element = document.createElement('div');
console.log(element.isConnected); // Returns false
document.body.append(element);
console.log(element.isConnected); // Returns true

가장 쉬운 방법:

const cond = document.getElementById('elem') || false
if (cond) {
    //does
} else {
    //does not
}

페이지 전체가 아닌 엄밀하게 보이는 DOM에서 필요한 경우 view-js와 같은 것을 사용합니다(my lib는 원하는 만큼 두들겨 줍니다).


<script src='https://view-js.glitch.me/view-main.js'></script>
<script>
elem = $sel('#myelem');
if (isVis(elem)) { //yes } else { //no }
</script>

function test() {
  pt = document.querySelector('#result')
  iv = document.querySelector('#f')
  
  cond = document.querySelector('#'+iv.value) || false
  
if (cond) {
    pt.innerText = 'Found!'
} else {
    pt.innerText = 'Not found!'
    }
}
  
Enter an id to see if it exists: <input id='f'></input>
<button onclick='test()'>Test!</button>

<br />
<p id='result'>I am a p tag. I will change depending on the result.</p>
<br />
<div id='demo'>I am a div. My id is demo.</div>

Mozilla Developer Network에서:

이 함수는 페이지 본문에 요소가 있는지 확인합니다.contains()는 포함이며 본문에 포함되어 있는지 여부를 판단하는 것은 isInPage의 의도가 아니기 때문에 이 케이스는 명시적으로 false를 반환합니다.

function isInPage(node) {
  return (node === document.body) ? false : document.body.contains(node);
}

node는 <body>에서 확인하는 노드입니다.

parentNode 속성이 null인지 확인할 수 있습니다.

그것은,

if(!myElement.parentNode)
{
    // The node is NOT in the DOM
}
else
{
    // The element is in the DOM
}

가장 쉬운 해결책은 베이스를 확인하는 것입니다.요소가 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 > 0) {
    // Do stuff here if the element exists
} else {
    // Do stuff here if the element does not exist
}

jQuery 솔루션:

if ($('#elementId').length) {
    // element exists, do something...
}

를 사용하여 했고, "jQuery"는 없었습니다.$('#elementId')[0]사용할 수 있습니다.

csuldcat의 솔루션이 가장 좋은 솔루션인 것 같습니다만, iframe과 같이 JavaScript 코드가 실행되고 있는 것과는 다른 문서에 있는 요소에서 올바르게 동작하려면 약간의 수정이 필요합니다.

YOUR_ELEMENT.ownerDocument.body.contains(YOUR_ELEMENT);

「」의 .ownerDocument한 구식이 document(요소의 소유자 문서를 참조하거나 참조하지 않을 수 있습니다).

Torazaburo는 비국소적인 요소들과도 함께 작동하는 훨씬 더 간단한 방법을 게시했습니다, 그러나 불행하게도, 그것은 그것을 사용합니다.baseURI이 속성은 현재 브라우저 간에 균일하게 구현되지 않습니다(WebKit 기반에서만 사용할 수 있습니다).비슷한 방법으로 사용할 수 있는 다른 요소나 노드 속성을 찾을 수 없었기 때문에 당분간은 위의 솔루션이 좋다고 생각합니다.

부모를 반복하는 대신 요소가 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 너비 및 높이 요소의 모서리 케이스를 처리하려면 부모 항목을 반복하여 두 번 확인할 수 있습니다.document.body:

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;
}

다른 옵션은 element.closest입니다.

element.closest('body') === null

이 코드는 나에게 효과가 있고, 나는 아무런 문제가 없었다.


    if(document.getElementById("mySPAN")) {
        // If the element exists, execute this code
        alert("Element exists");
    }
    else {
        // If the element does not exist execute this code
        alert("Element does not exists");
    }

요소가 다음 요소의 자식인지 확인합니다.<html>경유:

const div = document.createElement('div');
document.documentElement.contains(div); //-> false

document.body.appendChild(div);
document.documentElement.contains(div); //-> true

난 이걸 더 많이 다뤘어. 이-돔-디테일한 곳에서.

를 사용하여 요소가 다른 요소의 하위 요소인지 확인할 수도 있습니다.나는 합격했다document페이지 DOM 에 존재하는 요소는, 그 하위 요소이기 때문에, 검색하는 부모 요소로서document.

jQuery.contains( document, YOUR_ELEMENT)

jQuery를 사용한 심플한 솔루션:

$('body').find(yourElement)[0] != null
// This will work prefectly in all :D
function basedInDocument(el) {

    // This function is used for checking if this element in the real DOM
    while (el.parentElement != null) {
        if (el.parentElement == document.body) {
            return true;
        }
        el = el.parentElement; // For checking the parent of.
    } // If the loop breaks, it will return false, meaning
      // the element is not in the real DOM.

    return false;
}

HTML 요소를 제외한 모든 기존 요소에는 parentElement 세트가 있습니다.

function elExists (e) { 
    return (e.nodeName === 'HTML' || e.parentElement !== null);
};
  • 요소가 에 있는 경우DOM, 그것의 부모 또한 안에 있어야 한다.
  • 그리고 마지막 조부모는 그 사람이어야 해document

그래서 우리는 원소의 원소로 루프하는 것을 확인합니다.parentNode우리가 마지막 조부모가 될 때까지 나무

사용방법:

/**
 * @param {HTMLElement} element - The element to check
 * @param {boolean}     inBody  - Checks if the element is in the body
 * @return {boolean}
 */
var isInDOM = function(element, inBody) {
    var _ = element, last;

    while (_) {
        last = _;
        if (inBody && last === document.body) { break;}
        _ = _.parentNode;
    }

    return inBody ? last === document.body : last === document;
};

이 병아리는 모든 경우에 해당합니다.

function del() {
//chick if dom has this element 
//if not true condition means null or undifind or false .

if (!document.querySelector("#ul_list ")===true){

// msg to user
    alert("click btn load ");

// if console chick for you and show null clear console.
    console.clear();

// the function will stop.
    return false;
}

// if its true function will log delet .
console.log("delet");

}

다음 명령을 사용하여 요소가 DOM에 존재하는지 여부를 반환합니다.

return !!document.getElementById('myElement');

요소의 존재 여부를 확인합니다.

const elementExists = document.getElementById("find-me");
if(elementExists){
    console.log("have this element");
}else{
    console.log("this element doesn't exist");
}

질문 때문에 여기 착륙했으니까.위에서 제시한 해결책 중 문제를 해결하지 못하는 것은 거의 없습니다.몇 번 찾아본 결과, 현재 뷰포트에 노드가 있는지 없는지, 본문에 답이 있는지 아닌지를 해결할 수 있는 솔루션을 인터넷에서 찾았습니다.

function isInViewport(element) {
    const rect = element.getBoundingClientRect();
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
}

isInViewport(document.querySelector('.selector-i-am-looking-for'));

링크는 시간이 지나면 사용할 수 없게 될 수 있으므로 이 스니펫은 백업으로 보관하기 위해 여기서 가져옵니다.링크에서 설명을 확인하십시오.

그리고, 대부분의 경우 무시당하기 때문에, 코멘트에 투고할 생각은 없었습니다.

사용하다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');
}

이 접근방식이 마음에 들었습니다.

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

언급URL : https://stackoverflow.com/questions/5629684/how-can-i-check-if-an-element-exists-in-the-visible-dom

반응형