Jak mogę sprawdzić, czy element istnieje w widoku DOM?

Jak sprawdzić pierwiastek na istnienie bez użycia metody getElementById?

Ustawiłem demo na żywo w celach informacyjnych. Tutaj również wydrukuję kod:

<!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>

Zasadniczo powyższy kod pokazuje, że element jest przechowywany w zmiennej, a następnie usuwany z DOM. Mimo że element został usunięty z drzewa DOM, zmienna zachowuje element w stanie, w jakim był zadeklarowany po raz pierwszy. Innymi słowy, nie jest to odniesienie na żywo do samego elementu, a raczej repliki. W rezultacie sprawdzenie wartości zmiennej (elementu) pod kątem istnienia zapewni nieoczekiwany wynik.

Funkcja isNull jest moją próbą sprawdzenia istnienia elementów ze zmiennej i działa, ale chciałbym wiedzieć, czy jest łatwiejszy sposób na osiągnięcie tego samego wyniku.

PS: interesuje mnie również, dlaczego zmienne JavaScript zachowują się w ten sposób, jeśli ktoś zna jakieś dobre artykuły związane z tym tematem.

Author: Peter Mortensen, 2011-04-12

27 answers

Wydaje się, że niektórzy ludzie lądują tutaj i po prostu chcą wiedzieć, czy element istnieje (trochę inny niż pierwotne pytanie).

To tak proste, jak użycie dowolnej metody wyboru przeglądarki i sprawdzenie jej pod kątem wartości True (ogólnie).

Na przykład, gdyby mój element miał id z "find-me", mógłbym po prostu użyć...

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

Jest to parametr zwracający odniesienie do elementu lub null. Jeśli musisz mieć Boolean value, wystarczy rzucić !! przed wywołaniem metody.

Ponadto, można użyć niektórych z wielu innych metod, które istnieją do znajdowania elementów, takich jak (wszystkie living off document):

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

Niektóre z tych metod zwracają NodeList, więc należy sprawdzić jej właściwość length, Ponieważ a NodeList jest obiektem, a zatem prawdziwym.


Do faktycznego określenia, czy element istnieje jako część widoczny DOM (podobnie jak pierwotnie zadane pytanie), Csuwldcat zapewnia lepsze rozwiązanie niż rolowanie własnego (jak ta odpowiedź kiedyś zawierała). Czyli użyć contains() metoda na elementach DOM.

Możesz go tak wykorzystać...

document.body.contains(someReferenceToADomElement);
 607
Author: alex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-29 01:25:18

Użyj getElementById() jeśli jest dostępny.

Również, tutaj jest łatwy sposób, aby to zrobić z jQuery:

if ($('#elementId').length > 0) {
  // Exists.
}

A jeśli nie możesz korzystać z bibliotek innych firm, po prostu trzymaj się JavaScript bazowego:

var element =  document.getElementById('elementId');
if (typeof(element) != 'undefined' && element != null)
{
  // Exists.
}
 337
Author: Kon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-29 01:31:27

Za pomocą węzła .zawiera API DOM , można łatwo sprawdzić obecność dowolnego elementu na stronie (obecnie w DOM):

document.body.contains(YOUR_ELEMENT_HERE);

Notatka między przeglądarkami: obiekt document w Internet Explorerze nie ma metody contains() - aby zapewnić kompatybilność między przeglądarkami, użyj zamiast tego document.body.contains().

 214
Author: csuwldcat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-29 01:36:25

Po prostu robię:

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

To działa dla mnie i nie miał z tym jeszcze żadnych problemów...

 79
Author: Anomaly,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-29 01:35:25

Możesz po prostu sprawdzić, czy właściwość parentNode jest null.

Czyli

if(!myElement.parentNode)
{
    // The node is NOT in the DOM
}
else
{
    // The element is in the DOM
}
 12
Author: mikechambers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-29 01:34:00

From Mozilla Developer Network :

Ta funkcja sprawdza, czy element znajduje się w ciele strony. Ponieważ contains() jest inkluzywne i określenie, czy ciało zawiera siebie, nie jest intencją isInPage, w tym przypadku jawnie zwraca false.

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

Node jest węzłem, który chcemy sprawdzić w .

 12
Author: Ekramul Hoque,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-29 01:40:19

Najprostszym rozwiązaniem jest sprawdzenie baseURI właściwość, która jest ustawiana tylko wtedy, gdy element zostanie wstawiony do DOM, a po jego usunięciu powróci do pustego łańcucha.

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>
 7
Author: Peter Mortensen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-29 01:43:00

Rozwiązanie JQuery:

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

To działało u mnie przy użyciu jQuery i nie wymagało $('#elementId')[0] do użycia.

 5
Author: Code Buster,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-19 00:26:36

Prosty sposób sprawdzenia czy element istnieje można wykonać za pomocą kodu jednoliniowego jQuery.

Oto poniższy kod:

if ($('#elementId').length > 0) {
    // Do stuff here if the element exists
} else {
    // Do stuff here if the element does not exist
}
 5
Author: Ravi Agrawal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-29 01:56:02

Ten kod działa dla mnie i nie miałem z nim żadnych problemów.


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

 4
Author: Mohammad Ayoub Khan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-29 02:04:55

Wolę używać właściwości node.isConnected (Visit MDN ).

Uwaga: zwróci to wartość true, Jeśli element zostanie dołączony do katalogu cieni, co może nie być pożądanym zachowaniem wszystkich.

Przykład:

const element = document.createElement('div');
console.log(element.isConnected); // Returns false
document.body.append(element);
console.log(element.isConnected); // Returns true
 4
Author: Robbendebiene,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-14 19:15:05

Rozwiązanie Csuwldcat wydaje się być najlepsze z całej gamy, ale potrzebna jest niewielka modyfikacja, aby działało poprawnie z elementem, który znajduje się w innym dokumencie niż uruchomiony kod JavaScript, na przykład iframe:

YOUR_ELEMENT.ownerDocument.body.contains(YOUR_ELEMENT);

Zwróć uwagę na użycie właściwości ownerDocument, w przeciwieństwie do zwykłej starej document (która może lub nie musi odnosić się do dokumentu właściciela elementu).

Torazaburo opublikował jeszcze prostszą metodę , która działa również z nielokalnymi elements, ale niestety używa właściwości baseURI, która nie jest w tej chwili jednolicie zaimplementowana we wszystkich przeglądarkach (mogłem ją uruchomić tylko w bazujących na Webkitach ). Nie mogłem znaleźć żadnych innych właściwości elementu lub węzła, które mogłyby być używane w podobny sposób, więc myślę, że na razie powyższe rozwiązanie jest tak dobre, jak to tylko możliwe.

 3
Author: DoctorDestructo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-29 01:45:39

Zamiast iteracji parents, możesz po prostu uzyskać obwiedniowy prostokąt, który jest zerami, gdy element jest odłączony od DOM:

function isInDOM(element) {
    if (!element)
        return false;
    var rect = element.getBoundingClientRect();
    return (rect.top || rect.left || rect.height || rect.width)?true:false;
}

Jeśli chcesz obsłużyć rozmiar krawędzi elementu o zerowej szerokości i wysokości w zero top i zero left, możesz sprawdzić dwukrotnie, iteracją parents aż do 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;
}
 3
Author: Erez Pilosof,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-29 01:53:37

Inną opcją jest element.najbliższe :

element.closest('body') === null
 2
Author: Brian M. Hunt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-29 01:56:25

Możesz również użyć jQuery.contains, która sprawdza czy element jest potomkiem innego elementu. Przekazałem document jako element nadrzędny do wyszukiwania, ponieważ wszystkie elementy, które istnieją na stronie DOM, są potomkiem document.

jQuery.contains( document, YOUR_ELEMENT)
 1
Author: nitinkhuranas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-09 07:36:29

Sprawdź czy element jest potomkiem <html> poprzez Node::contains():

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

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

Omówiłem to i więcej w is-dom-wolnostojący .

 1
Author: Steven Vachon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-06-24 19:26:31

Proste rozwiązanie z jQuery:

$('body').find(yourElement)[0] != null
 1
Author: mateusmaso,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-29 01:34:25
// 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;
}
 1
Author: qandil afa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-29 02:00:10

Wszystkie istniejące elementy mają ustawiony parentElement, z wyjątkiem elementu HTML!

function elExists (e) { 
    return (e.nodeName === 'HTML' || e.parentElement !== null);
};
 1
Author: Jonah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-29 02:02:53
  • Jeśli element jest w DOM, jego rodzice powinni być również w
  • a ostatnim dziadkiem powinien być document

Więc aby sprawdzić czy po prostu zapętlamy się do drzewa elementu parentNode aż dotrzemy do ostatniego

Użyj tego:

/**
 * @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;
};

 1
Author: silassare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-03-25 08:40:03

Ten warunek chick wszystkie przypadki.

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");

}
 1
Author: Omar bakhsh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-04-07 14:21:35

Podobało mi się to podejście:

var elem = document.getElementById('elementID');

if (elem)
    do this
else
    do that

Również

var elem = ((document.getElementById('elemID')) ? true:false);

if (elem)
    do this
else
    do that
 0
Author: Hugh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-29 01:41:40

Użyj querySelectorAll z forEach,

document.querySelectorAll('.my-element').forEach((element) => {
  element.classList.add('new-class');
});

Jako przeciwieństwo:

const myElement = document.querySelector('.my-element');
if (myElement) {
  element.classList.add('new-class');
}
 0
Author: Rafal Enden,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-29 01:54:53

Spróbuj wykonać następujące czynności. Jest to najbardziej niezawodne Rozwiązanie:

window.getComputedStyle(x).display == ""

Na przykład,

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'
 0
Author: dexiang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-29 01:57:17

Użyj poniższego polecenia, aby zwrócić, czy element istnieje w DOM:

return !!document.getElementById('myElement');
 0
Author: Renato Gonçalves,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-17 08:43:21

Zaznacz element exist or not

const elementExists = document.getElementById("find-me");
if(elementExists){
    console.log("have this element");
}else{
    console.log("this element doesn't exist");
}
 0
Author: MD SHAYON,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-25 02:47:23

Jak wylądowałem tutaj z powodu pytania. Niewiele z powyższych rozwiązań nie rozwiązuje problemu. Po kilku poszukiwaniach znalazłem rozwiązanie w internecie, które pod warunkiem, że węzeł jest obecny w bieżącym viewporcie, gdzie odpowiedzi próbowałem rozwiązuje to jest obecny w ciele, czy nie.

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'));

Fragment jest pobrany z tutaj , aby zachować jako kopię zapasową, ponieważ linki mogą być niedostępne po pewnym czasie. Sprawdź link, aby uzyskać wyjaśnienie.

I nie zamierzał pisać w komentarz, jak w większości przypadków, są ignorowane.

 0
Author: ssi-anik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-24 05:35:32