0

EDIT: This is the dumbest question I've asked on SO. I'll keep it, to remind myself not to ask questions too quickly.

How can I check if the DOM node I have selected is the html node? I have noticed that it does not have the usual properties. For example:

var div = document.getElementsByTagName('div')[0];
var html = document.getElementsByTagName('html');

div instanceof HTMLElement; // true
html instanceof HTMLElement; // false

div.tagName; // "DIV"
html.tagName; // undefined

In particular, I would like a check that works for all DOM nodes (div, span, etc.). The issue is that my code crawls up the DOM and checks for a certain property; if the code does not find the property, it reaches the html node and throws an error because of this line:

if (node.tagName.toUpperCase() !== 'OBJECT') { }

This throws a TypeError when node is the html node, because node.TagName is undefined.

Thanks in advance.

2 Answers 2

2

The problem is that you are looking at the array returned by getElementsByTagName instead of the first element returned. Try this:

var div = document.getElementsByTagName('div')[0];
var html = document.getElementsByTagName('html')[0]; // notice [0]

div instanceof HTMLElement; // true
html instanceof HTMLElement; // true

div.tagName; // "DIV"
html.tagName; // "HTML"

Note: tested in in Chrome Developer Tools Version 30.0.1599.101 m

Sign up to request clarification or add additional context in comments.

Comments

1

Your variable html is not a single node, hence why it is different than div. Add the missing [0] like you do for your div reference!

1 Comment

Yeah, in the console you will get an undefined, because you're setting a var but not doing anything with it. Try var html = document.getElementsByTagName('html')[0]; console.log(html); This will produce an expandable tree of the html node.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.