Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an element is the body?

From chrome console:

var body = $("body");
=>  undefined
body
=>  [<body class=​"ask-page">​…​</body>​]
body.tagName
=>  undefined
body.nodeName
=>  undefined

So if I have an element reference, how can I know if it's the body?

(JQuery welcome!)

like image 446
Tony R Avatar asked Feb 28 '12 19:02

Tony R


People also ask

How do you know if an element is in DOM?

contains DOM API, you can check for the presence of any element in the page (currently in the DOM) quite easily: document. body. contains(YOUR_ELEMENT_HERE);

Can the elements body be replaced by body?

You can only replace the HTML's body element with PHP if you are outputting the HTML with PHP (changing it before outputting it). PHP works server-side, so once the HTML reaches the client it cannot modify it.

How do you know if an element is present?

In order to check if an element is present on a webpage, we make use of driver. findElements() method. As we know that driver. findElements() method returns a list of webElements located by the “By Locator” passed as parameter.


1 Answers

Try this comparison with sample usage of plain JavaScript and jQuery:

function isBody(el) {
  return document.body === el;
}

isBody(document.getElementById('child').parentElement); // => true
isBody($('#child').parent().get(0)); // => true
like image 146
maerics Avatar answered Sep 24 '22 11:09

maerics