-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
  • 981
  • 2
  • 14
  • 30

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,645
  • 9
  • 68
  • 76
1

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

Anubhav
  • 6,746
  • 5
  • 20
  • 32