Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check an element retrieved from DOM is still present in DOM

Let's say I got a DOM element, as a param of an event, for example click.

$(document).click(function() {
    myElement = $(this);
});

How can I check later that myElement is still in the DOM? I can't use .length or any other things like that because it still refer to the saved element and the state of the DOM at this moment, right?

like image 320
Valentin Fournier Avatar asked Oct 08 '12 16:10

Valentin Fournier


3 Answers

You can check element parent:

function isInDom(obj) {
    var root = obj.parents('html')[0] 
    return !!(root && root === document.documentElement);
}


if(isInDom(myElement)) {
     ...
}

Here's working fiddle: http://jsfiddle.net/vnxhQ/7/

like image 115
Inferpse Avatar answered Oct 04 '22 07:10

Inferpse


You're probably looking for Node.isConnected.

like image 36
aryzing Avatar answered Oct 04 '22 05:10

aryzing


The only reliable way I see so far is to check if the element is inside document.getElementsByTagName('*')

function isInDoc(element)
{
  var elements=document.getElementsByTagName(element.tagName);
  for(var i=0;i<elements.length;++i)
  {
    if(elements[i]===element)return true;
  }
  return false;
}

Demo: http://jsfiddle.net/doktormolle/hX8eN/


<edit>

Node.contains() seems to be supported by all major browsers, so I would finally suggest this:

if(document.documentElement.contains(myElement))

Demo: http://jsfiddle.net/doktormolle/LZUx3/

like image 34
Dr.Molle Avatar answered Oct 04 '22 07:10

Dr.Molle