638

How do you test an element for existence without the use of the getElementById method?

I have set up a live demo for reference. I will also print the code on here as well:

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

Basically the above code demonstrates an element being stored into a variable and then removed from the DOM. Even though the element has been removed from the DOM, the variable retains the element as it was when first declared. In other words, it is not a live reference to the element itself, but rather a replica. As a result, checking the variable's value (the element) for existence will provide an unexpected result.

The isNull function is my attempt to check for an elements existence from a variable, and it works, but I would like to know if there is an easier way to accomplish the same result.

PS: I'm also interested in why JavaScript variables behave like this if anyone knows of some good articles related to the subject.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Justin Bull
  • 7,785
  • 6
  • 26
  • 30
  • 28
    Actually it is a live reference to the element itself, it's just not in a document any more. That functionality is required because you can actually pull an element out of the DOM and then put it back in later with all event handlers/etc still attached to it. As for why JS variables act like that? Because it would be incredibly annoying if they didn't. JS only deletes variables when you no longer have ANY references to them. The language has no way of knowing which references you deem important and which you think are worthless. –  Apr 12 '11 at 02:45
  • @cwolves Interesting. I've encountered this many times before and never really thought much of it. In fact, in my current project, I'm saving elements in an array before I make any changes to them, just in case I want to revert the changes. – Justin Bull Apr 12 '11 at 03:19
  • 1
    Garbage collection runs from time to time and deletes everything it thinks it can. It seems pretty lousy in most browsers, but is getting better as developers realise that some browsers run for days or weeks between restarts, so good garbage collection is vital for browser performance. Web developers can help by deleting properties (and hence references to things in memory) that are no longer required. – RobG Apr 12 '11 at 04:13
  • 2
    @JustinBull be careful with storing copies of the elements to revert. When storing a DOM element in an array, a reference to the DOM element is stored, not a copy, so changes made to the DOM element will be reflected when referencing the array's element. This is the case with all objects in javascript (variables of type 'object'). – Anthony DiSanti Sep 07 '11 at 06:50

27 Answers27

806

It seems some people are landing here, and simply want to know if an element exists (a little bit different to the original question).

That's as simple as using any of the browser's selecting method, and checking it for a truthy value (generally).

For example, if my element had an id of "find-me", I could simply use...

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

This is specified to either return a reference to the element or null. If you must have a Boolean value, simply toss a !! before the method call.

In addition, you can use some of the many other methods that exist for finding elements, such as (all living off document):

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

Some of these methods return a NodeList, so be sure to check its length property, because a NodeList is an object, and therefore truthy.


For actually determining if an element exists as part of the visible DOM (like the question originally asked), Csuwldcat provides a better solution than rolling your own (as this answer used to contain). That is, to use the contains() method on DOM elements.

You could use it like so...

document.body.contains(someReferenceToADomElement);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
alex
  • 479,566
  • 201
  • 878
  • 984
  • I noticed just checking `parentNode` is good enough (will be null if element is removed). Would you say this is just as good? [jsBin](http://jsbin.com/iroqe5) – Justin Bull Apr 12 '11 at 02:46
  • @Jabes88 Good thinking. If it works on all browsers, then go for it :) – alex Apr 12 '11 at 02:51
  • Ack! Simply checking `parentNode` does not work in IE7 or IE8. However, your suggested method seems to work in all versions of IE as well as Chrome, FF, Safari, and Opera. Thanks again for your help. – Justin Bull Apr 12 '11 at 03:32
  • @JustinBull, well simply checking for `parentNode` won't work anywhere. If your element's parent has been removed from the DOM, then your element will have a parentNode, but won't be part of the DOM – andras Jan 30 '12 at 16:35
  • 3
    Even shorter: `var elementInDom = function( el ) { while ( el = el.parentNode ) if ( el === document ) return true; return false; }` – bennedich Feb 26 '12 at 22:48
  • Your answer did not work for me. I used getElementById and then checked for null and undefined as in Kon's answer. `if(myElement != null && typeof myElement !== 'undefined') {` etc... – Buttle Butkus Feb 10 '13 at 20:56
  • 2
    @ButtleButkus Read the actual question. That solution you used doesn't make sense as `getElementById()` *will* return a reference to a DOM element or `null`, therefore, using `typeof` (especially on the RHS) is wrong (if it weren't defined, the LHS condition would throw a `ReferenceError`). – alex Feb 10 '13 at 22:38
  • I see now the asker did not want to use getElementById for some reason. Still, the code did not work for me, perhaps due to some other issue. But it seems like it worked for others. Unfortunately I can't take back my downvote unless you edit the question. If you make some minor edit I will gladly undo the vote. – Buttle Butkus Feb 11 '13 at 08:48
  • 2
    Is there any reason to use this over what was posted below: `document.body.contains()` which seems to have very good browser support? – crush Jun 18 '13 at 15:29
  • @crush Just saw it. Doesn't look like it. I'll put a pointer in my answer to that one. – alex Jun 18 '13 at 21:32
  • @csuwldcat I was trying to make it visible because this answer is the accepted one. The edit was meant to convey *hey, csuwldcat has this better answer but you probably won't find it below, now you can follow this link and you should vote for it*. It wasn't done to be un-nice in any way. If you still feel that way, feel free to edit my answer. It will go into the moderation queue for the community to decide. – alex Jun 27 '13 at 02:12
  • @alex - no, you're right - your answer has a ton of votes and is the selected one, so it's probably better that the solution appears for people first. – csuwldcat Jun 27 '13 at 04:45
  • @JohnSyrinek That was the question. – alex Oct 24 '13 at 23:01
  • `document.contains(someReferenceToADomElement);` what a revelation!!! the answer is so long, I wish it would just highlight that one line of code. – jrz Mar 25 '15 at 21:41
  • 1
    @Jonz Removed the *old* answer part, don't forget to go and vote up [csuwldcat](http://stackoverflow.com/a/16820058/31671) – alex Mar 25 '15 at 23:22
  • Just wanted to second crush's comment about browser support. According to MDN, none of IE supports document.contains(). In addition to linking to @csuwildcat's answer, could we just replace the suggestion with document.body.contains()? https://developer.mozilla.org/en-US/docs/Web/API/Document – launchoverit Aug 19 '16 at 16:16
  • plus 1 for !! part. could you explain or give ref link to its explanation ? – Zameer Fouzan Oct 04 '17 at 12:54
  • For @ZameerFouzan and those wondering about `!!`, it's done like this: `var elementExists = !!document.getElementById("find-me");` In that case, it'll return boolean value based on whether the element exists or not. – Don Cullen Apr 01 '20 at 17:51
  • These methods don't work **should your element be within a shadow DOM**, trying to find a way to make it work in this scenario: the best I can think of would be to check for an offsetWidth or any other layout related property. It would prevent 0 sized elements from being detected though, so it's far from bulletproof – daformat Oct 03 '21 at 08:42
  • See @Robbendebiene answer for a working method **with shadow DOMs**: https://stackoverflow.com/a/62300560/1358317 – daformat Oct 03 '21 at 09:11
414

Use getElementById() if it's available.

Also, here's an easy way to do it with jQuery:

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

And if you can't use third-party libraries, just stick to base JavaScript:

var element =  document.getElementById('elementId');
if (typeof(element) != 'undefined' && element != null)
{
  // Exists.
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kon
  • 27,113
  • 11
  • 60
  • 86
  • 2
    For the project I'm working on, I'm not able to use a library. Good-ol' fashion raw code only. I'm aware of that jQuery method, but it does not work on elements not wrapped in the jQuery container. For example, `$('#elementId')[0].length` would not produce the same result. – Justin Bull Apr 12 '11 at 02:38
  • 1
    To say this is wrong, I also had to prove to myself this was incorrect. So to explain, type this in your browser's console: `$('body').parent();` vs `$('
    ').parent();`. Both return **1** for `.length` - but you'll see that the **body** has a parent, and if you do enough `.parent().parent()` you'll reach the **document** which is the top of the DOM Tree. While on the other hand, **
    ** exists in memory and has no parent, but returns length of 1 which just counts the elements in the jQuery object. I suggest editing your question to keep SO clean :)
    – Mike Mar 23 '12 at 19:22
  • 16
    Is there any good reason for such a complicated if statement in the second code example? Why not simply `if (element) {}`? When element is undefined or null then this expression is false. If element is a DOM element then the expression is true. – kayahr Dec 18 '12 at 10:14
  • 4
    @kayahr It is far too complicated. `getElementById()` is spec'd to return `null` if it didn't find the element, so checking for a *truthy* returned value is all that's needed. – alex Feb 06 '13 at 04:44
  • 2
    Note that the element must have an id to be able catch via getElementById() – burak emre Mar 23 '13 at 17:54
  • 5
    I think that's just common sense. – Kon Mar 23 '13 at 21:42
  • if the element has an `id`, `if (document.getElementById('elementId')) ...` is the obvious answer. +1 – bozdoz Jul 31 '14 at 18:28
  • 9
    `getElementById` should never return `undefined`. In any case, the `element != null` check would pick this up. –  Sep 28 '14 at 09:43
  • Testing the above code I got this error " Expected '===' and instead saw '==' " – ShapCyber Jun 06 '16 at 01:24
  • Which method is faster? Did anyone tested it yet? – Black Oct 22 '16 at 07:41
  • You don't need the >0, since length is false. Be aware, sometimes a browser will throw a "can't find length of undefined" error, depending on how you write this. – Longblog May 16 '17 at 22:46
  • @ShapCyber Sounds like a linting rule you have – alex Apr 27 '18 at 10:30
256

Using the Node.contains DOM API, you can check for the presence of any element in the page (currently in the DOM) quite easily:

document.body.contains(YOUR_ELEMENT_HERE);

CROSS-BROWSER NOTE: the document object in Internet Explorer does not have a contains() method - to ensure cross-browser compatibility, use document.body.contains() instead.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
csuwldcat
  • 8,021
  • 2
  • 37
  • 32
  • 4
    This seems like the ultimate answer to this problem...and its support, if MDN is to be believed is quite good. – crush Jun 18 '13 at 15:24
  • 3
    This is the best answer. Note that just checking `document.contains()` should be enough. – alex Jun 18 '13 at 21:39
  • @csuwldcat It worked for me, at least in Chrome with `document.contains(document.documentElement)`. `document` does have `Node` on its prototype chain, as far as I can tell (`document`->`HTMLDocument`->`Document`->`Node`) – alex Jun 26 '13 at 05:40
  • 4
    This is indeed the best answer: - it's a web standard - it's very well supported (somewhat surprisingly it doesn't appear in Firefox until version 9, I'm guessing because it was a non-standard function invented in IE that wasn't standardized until later) - it must be the fastest because it uses a single call to a native API – jrz Mar 26 '15 at 15:00
  • Can/Should this be used to target specific elements via class or ID? What's the syntax? – Lee Saxon Jan 01 '16 at 07:21
  • 10
    @LeeSaxon The syntaxis is `document.body.contains([selector])`, i.e. `document.body.contains(document.getElementById('div')` – eduardo a Jan 19 '18 at 15:56
  • What about `Node.isConnected()` [link](https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected) – Marc K. Jan 12 '20 at 01:03
  • @MarcK. that API didn't exist when I first added this answer, but the other issue is that Node.isConnected() isn't compatible with IE and old non-Chromium Edge, so I think we're still going to need to use body.contains() into the foreseeable future. – csuwldcat Jan 13 '20 at 18:43
  • [alex](https://stackoverflow.com/users/31671/alex) you're right `document.contains()` is enough if you want to check the entire DOM, but to check the visible DOM as the question is originally asking `.body` is necessary – Mustapha-Belkacim Jun 24 '20 at 17:15
99

I simply do:

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

It works for me and had no issues with it yet...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Stuyvenstein
  • 2,340
  • 1
  • 27
  • 33
  • 2
    This has nothing to do with the original question though. The OP wants to know if a reference to a DOM element is part of the visible DOM or not. – alex Mar 13 '13 at 11:27
  • 1
    This answer works well, but only when the element has an `id`. The better solution that answers the question *How to check if element exists in the visible DOM?* with any element, even elements without `id`s is to do `document.body.contains(element)`. – Edward Dec 15 '15 at 20:50
  • @Edward This is something completely different to `contains()` – alex Jan 27 '16 at 16:37
  • I get that. I was just suggesting in my comment that other answers are better and more suited to the question. – Edward Jan 28 '16 at 17:06
  • This won't check the visible DOM. Will check all the DOM – Broda Noel Jul 24 '16 at 20:39
  • For Type Script shoud be if(document.getElementById("myElementId").lenght>0) – Andrii Jul 05 '20 at 09:14
33

I prefer to use the node.isConnected property (Visit MDN).

Note: This will return true if the element is appended to a ShadowRoot as well, which might not be everyone's desired behaviour.

Example:

const element = document.createElement('div');
console.log(element.isConnected); // Returns false
document.body.append(element);
console.log(element.isConnected); // Returns true
element.remove();
console.log(element.isConnected); // Returns false
joe
  • 3,752
  • 1
  • 32
  • 41
Robbendebiene
  • 4,215
  • 3
  • 28
  • 35
31

Easiest way:

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

If needed in strictly visible DOM, meaning not on entire page, use something like view-js (my lib so beat it up as much as you want)


<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>
Mehan Alavi
  • 278
  • 3
  • 17
Blaze612 YT
  • 594
  • 7
  • 13
13

From Mozilla Developer Network:

This function checks to see if an element is in the page's body. As contains() is inclusive and determining if the body contains itself isn't the intention of isInPage, this case explicitly returns false.

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

node is the node we want to check for in the <body>.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ekramul Hoque
  • 4,957
  • 3
  • 30
  • 31
13

You could just check to see if the parentNode property is null.

That is,

if(!myElement.parentNode)
{
    // The node is NOT in the DOM
}
else
{
    // The element is in the DOM
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mikechambers
  • 3,047
  • 3
  • 24
  • 31
  • 1
    I know this is an old question but this answer is exactly the kind of elegant simple solution to the question which I was looking for. – poby Apr 23 '13 at 18:18
  • 14
    @poby: It might seem elegant but it isn't really doing what was requested. It only checks if the element has a parent element. This doesn't imply that the element is in the visible DOM because maybe the parent element is not connected to it. – kayahr Jun 12 '13 at 06:58
  • One would have to go through all parent of parents to find out if last one is document. The other problem is it still could be outside of visible range or be covered or be not visible because of many other reasons. – Arek Bal Apr 06 '14 at 06:55
  • An element could also have a parentNode only by virtue of having been appended to a document fragment. –  Sep 28 '14 at 09:37
  • @kayahr on what conditions may an element is in the visible DOM but the parent node is not connected to it? – Eric Jan 20 '21 at 05:58
  • 1
    @Eric An element which has no parent node can't be connected to the document , that's right. But on the other hand when element has a parent node then this does NOT automatically mean that the element is connected to the document because the parent node may be disconnected and this means all child elements are also disconnected. So this check is wrong and does not do what it says. – kayahr Feb 10 '21 at 16:11
8

The easiest solution is to check the baseURI property, which is set only when the element is inserted in the DOM, and it reverts to an empty string when it is removed.

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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 5
    I didn't even know there was baseURI property on DOM nodes. What I like about this approach is that it uses a property of the element itself, which presumably means it would work even if the element is in a different document (e.g. an iframe). What I don't like about it is that it doesn't seem to work outside of Webkit. – DoctorDestructo Nov 29 '14 at 00:39
  • 1
    Careful as this will throw the following error if the element is not in the document: `Cannot read property 'baseURI' of null`. Example: `console.log(document.querySelector('aside').baseURI)` – Ian Davis Aug 01 '18 at 18:27
  • This method can't be used as it always prints the same string as of now. – Kagami Sascha Rosylight Jan 16 '20 at 12:25
  • Need a `try` `catch` for this method. – AGamePlayer Jul 15 '20 at 04:58
5

A simple way to check if an element exist can be done through one-line code of jQuery.

Here is the code below:

if ($('#elementId').length > 0) {
    // Do stuff here if the element exists
} else {
    // Do stuff here if the element does not exist
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ravi Agrawal
  • 87
  • 1
  • 5
5

This code works for me, and I didn't have any issues with it.


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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mohammad Ayoub Khan
  • 2,422
  • 19
  • 24
4

csuwldcat's solution seems to be the best of the bunch, but a slight modification is needed to make it work correctly with an element that's in a different document than the JavaScript code is running in, such as an iframe:

YOUR_ELEMENT.ownerDocument.body.contains(YOUR_ELEMENT);

Note the use of the element's ownerDocument property, as opposed to just plain old document (which may or may not refer to the element's owner document).

torazaburo posted an even simpler method that also works with non-local elements, but unfortunately, it uses the baseURI property, which is not uniformly implemented across browsers at this time (I could only get it to work in the WebKit-based ones). I couldn't find any other element or node properties that could be used in a similar fashion, so I think for the time being the above solution is as good as it gets.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
DoctorDestructo
  • 4,166
  • 25
  • 43
3

jQuery solution:

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

This worked for me using jQuery and did not require $('#elementId')[0] to be used.

alex
  • 479,566
  • 201
  • 878
  • 984
Code Buster
  • 195
  • 1
  • 11
  • Why is `$('#elementId')[0]` something to be avoided? – alex Jun 01 '16 at 11:32
  • Been long I answered this, So, using $('#elementId')[0] I believe you are always indicating that the value will be at the 0th index. This way you are always checking for the 1st occuring element. What is there were multiple checkboxes with same name, so like a radio button. That time the .length will be helpful. – Code Buster Mar 29 '18 at 07:28
3

Instead of iterating parents, you can just get the bounding rectangle which is all zeros when the element is detached from the DOM:

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

If you want to handle the edge case of a zero width and height element at zero top and zero left, you can double check by iterating parents till the 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;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
3

Another option is element.closest:

element.closest('body') === null
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Brian M. Hunt
  • 81,008
  • 74
  • 230
  • 343
3

Check if the element is a child of <html> via Node::contains():

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

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

I've covered this and more in is-dom-detached.

Steven Vachon
  • 3,814
  • 1
  • 30
  • 30
2

All existing elements have parentElement set, except the HTML element!

function elExists (e) { 
    return (e.nodeName === 'HTML' || e.parentElement !== null);
};
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Yunus
  • 181
  • 6
2

Use this command below to return whether or not the element exists in the DOM:

return !!document.getElementById('myElement');
hatef
  • 5,491
  • 30
  • 43
  • 46
2

Check 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");
}
MD SHAYON
  • 7,001
  • 45
  • 38
1

A simple solution with jQuery:

$('body').find(yourElement)[0] != null
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mateusmaso
  • 7,843
  • 6
  • 41
  • 54
  • 2
    ...or `$(document).find(yourElement).length !== 0` – Grinn Jun 04 '13 at 17:42
  • 1
    This exploits that `null == undefined`. The real returned value would be `undefined`. Comparing it against `null` is a bit weird. – alex Oct 24 '13 at 23:05
1
  • If an element is in the DOM, its parents should also be in
  • And the last grandparent should be the document

So to check that we just loop unto the element's parentNode tree until we reach the last grandparent

Use this:

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

silassare
  • 97
  • 1
  • 4
1
// 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;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
qandil afa
  • 32
  • 2
1

this condition chick all cases.

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

}
Omar bakhsh
  • 896
  • 11
  • 18
0

You can also use jQuery.contains, which checks if an element is a descendant of another element. I passed in document as the parent element to search because any elements that exist on the page DOM are a descendant of document.

jQuery.contains( document, YOUR_ELEMENT)
andrewgu
  • 1,562
  • 14
  • 23
0

Use querySelectorAll with forEach,

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

as the opposite of:

const myElement = document.querySelector('.my-element');
if (myElement) {
  element.classList.add('new-class');
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rafal Enden
  • 3,028
  • 1
  • 21
  • 16
0

As I landed up here due to the question. Few of the solutions from above don't solve the problem. After a few lookups, I found a solution on the internet that provided if a node is present in the current viewport where the answers I tried solves of it's present in the body or not.

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

console.log(
  isInViewport(document.querySelector('.selector-i-am-looking-for'))
);
<div class="selector-i-am-looking-for"></div>

The snippet is taken from HERE to keep as a backup as the links may be unavailable after some time. Check the link for an explanation.

And, didn't intend to post in the comment, as in most cases, they are ignored.

ssi-anik
  • 2,998
  • 3
  • 23
  • 52
-1

I liked this approach:

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

if (elem)
    do this
else
    do that

Also

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

if (elem)
    do this
else
    do that
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hugh
  • 15
  • 1