1

The question is quite straightforward. Is there a javascript only (no jQuery/other library pls) method of checking if an element created via javascript exists?

For instance, if I did this:

var foo=document.createElement("div");
document.getElementById("bar").appendChild(foo);

Would there be a way to check if foo already exists?

Jane Nguyen
  • 21
  • 1
  • 1
  • 4
  • If you don't give it an id or unique class, no. – Frédéric Hamidi Sep 28 '14 at 08:23
  • 1
    http://stackoverflow.com/questions/5629684/how-to-check-if-element-exists-in-the-visible-dom – Avinash Babu Sep 28 '14 at 08:24
  • 1
    What is an element that does not exist? Is this a philosophical question? – Chris Martin Sep 28 '14 at 08:25
  • @AvinashBabu, that isn't what I was looking for. infantDev's answer, however, did provide me with what I needed. – Jane Nguyen Sep 28 '14 at 08:53
  • What do you mean, check if foo already exists? The variable `foo` holds a *brand new element* that you just created; there is no way it could have already existed before calling `document.createElement`, because `document.createElement` always creates a new element. – Dagg Nabbit Sep 28 '14 at 09:02
  • @DaggNabbit If I were to run the function again it would create another foo, which is not something wanted. – Jane Nguyen Sep 28 '14 at 09:12
  • @user2644333 yes, it would create *another* element. It wouldn't "re-create" an element that "already exists." It would create *a different element*. The way your question is worded, it is pretty much meaningless, to the point where answerers need to *guess at what you mean*. – Dagg Nabbit Sep 28 '14 at 09:16
  • Why would an element you just created *not* exist? This question sounds like you experienced an error, and decided on this as a solution. What was the original problem? Because, as noted elsewhere, the question as phrased seems redundant. – David Thomas Sep 28 '14 at 09:46

2 Answers2

2

You could simply get the element by id and see if its not null.

var foo=document.createElement("div");
document.getElementById("bar").appendChild(foo);
foo.setAttribute("id","foo");
var ele = document.getElementById("foo");
if(ele !== null){ alert("Hi");}
Infant Dev
  • 1,659
  • 8
  • 24
  • 48
  • 2
    This answer introduces an assumption not made by the OP, which is that the element has an ID. –  Sep 28 '14 at 08:57
2

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
  • `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.` -- actually IDs do become global variables, see [section 7.2.4](https://html.spec.whatwg.org/multipage/browsers.html#named-access-on-the-window-object) of the HTML5 spec. Hard to tell whether it's relevant to the OP's problem, since the question is nonsense as it's worded now. – Dagg Nabbit Sep 28 '14 at 09:42
  • @DaggNabbit Thanks for reminding me of that. I'll tweak my answer. –  Sep 28 '14 at 09:48