Type casting Node to Element

2,712 views
Skip to first unread message

pablo platt

unread,
Jul 20, 2012, 5:22:07 PM7/20/12
to closure-comp...@googlegroups.com
Hi,

What's the difference between Node and Element?
The compiler complains that I'm giving him Node type while it expects Element type.
Is it ok to typecast to Element or am I just hiding the problem.

Code:

my.Component.prototype.createDom = function() {
    this.element_ = /** @type {Element} */ goog.dom.htmlToDocumentFragment(...);

var el = goog.dom.getElementByClass('myclass', /** @type {Element} */ (this.element_.previousSibling));

Thanks

John Lenz

unread,
Jul 20, 2012, 9:11:18 PM7/20/12
to closure-comp...@googlegroups.com

This is generally safe.  Node is returned from more generic methods.

pablo platt

unread,
Jul 21, 2012, 3:40:43 AM7/21/12
to closure-comp...@googlegroups.com
Thanks

Nick Santos

unread,
Jul 21, 2012, 3:14:31 PM7/21/12
to closure-comp...@googlegroups.com
For reference, see:
http://stackoverflow.com/questions/132564/whats-the-difference-between-an-element-and-a-node-in-xml
http://www.w3.org/TR/DOM-Level-2-Core/core.html

TL;DR: The DOM interface uses subclassing a lot to differentiate
between different types of Nodes: Elements, TextNodes,
HTMLInputElements, etc.

Many closure-library functions are pretty liberal in what they accept
(for example, only Elements can have CSS classes, but if you really
want to read the CSS class of a Node, go right ahead), but there are
some cases where it really matters (like in Components).

pablo platt

unread,
Jul 21, 2012, 4:27:06 PM7/21/12
to closure-comp...@googlegroups.com
Thanks
Reply all
Reply to author
Forward
0 new messages