foo
is not an element, it's a variable whose value is an element. There are different ways to interpret your question.
Is the value of the variable foo
a DOM element?
If you want to check if the variable foo
exists and has as its value an element, you can say
foo && typeof foo === 'object' && foo.nodeType
or something similar. This will check whether the element is any kind of Node
. To check for an element, use foo.nodeType === Node.ELEMENT_NODE
.
Is a particular HTML element in the DOM?
If you want to check if the element held in variable foo
is in the DOM, as opposed to having been created, but not yet inserted, then:
foo.baseURI
since baseURI
is set only upon DOM insertion. You might think you could check parentNode
, which is also not set until DOM insertion, but children of the non-inserted element, if any, will report a parentNode
, as will elements appended to a document fragment.
The other alternative is to use Node#contains
:
document.body.contains(foo)
which essentially does the same thing as scanning the entire DOM for the element:
Array.prototype.some.call(document.querySelector('*'), function(elt) {
return elt === foo;
})
In any case, this all seems pointless, because as far as I can imagine, if you hold a reference to a DOM element, and it's not not in the DOM, then it is in the DOM.
Is there already an element in the place I'm going to be inserting this one?
If you know where the element is going to go, in this case as a child of bar
, and that's enough to convince you that the "element already exists", you can check easily enough with something like:
document.getElementById("bar").children.length > 0
Is there already an element with this ID?
As other commenters and responders have noted, you can obviously find an element in the DOM if you have arranged to provide it with some uniquely identifiable characteristics, most likely an id.
I hope it's obvious that element ID is completely separate from the name of any JavaScript variables which happen to be holding references to that element. It is true that elements become available on the root (window) object under their ID or name attributes, a feature best left unused.
Was the element in the source HTML, or created by JavaScript?
From the wording of your question, it seems that you might be interested in whether the element was created by JS, as opposed to originating from the source HTML. There is no way I know of to detect that. If you are intent on doing so, override document.createElement
as follows:
document.createElement = (function() {
var old = document.createElement;
return function(tagName) {
var elt = old.call(document, tagName);
elt.I_CREATED_THIS = true;
return elt;
};
}());
> document.body.I_CREATED_THIS
undefined
> elt = document.createElement('span');
> elt.I_CREATED_THIS
true