-1

I want to know if a certain element is in the document.

I tried two options and i want to know which one is the best in terms of resources.

1)

var $lastParent = $(element).parents().last();
var nodeName = $lastParent.prop('nodeName').toLowerCase();
var isInDocument = (nodeName == 'html');

2)

var isInDocument = document.contains(element);
Fernando Gabrieli
  • 980
  • 3
  • 15
  • 31

2 Answers2

2

Try this:

document.contains

or

document.body.contains()

checkout eht IsInPage implementation here: https://developer.mozilla.org/en-US/docs/Web/API/Node.contains

Community
  • 1
  • 1
Tats_innit
  • 33,991
  • 10
  • 71
  • 77
1

You can use if ($(element).length) return true;

Anubhav
  • 7,138
  • 5
  • 21
  • 33