Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do .getElementById() and .innerHTML() bridge between HTML and the DOM?

Tags:

javascript

I've been writing Javascript for years, but just now realized I don't entirely understand how these "HTML-y" methods actually interact with the DOM.

My assumption is that when HTML is interpreted into the DOM, the browser keeps references as to which HTML element became which DOM node.

So for .getElementById when you select an element, the browser returns the relevant node by reference. Why not just do .getNodeById then and be more correct?

My assumption is that .innerHTML is interpreted by the browser into the DOM at runtime. However, in older browsers like IE7, .innerHTML cannot be used to create table nodes. This suggests to me that it was originally intended just to modify the text properties of existing nodes, but then it seems strange that it exists at all, and we don't just use .innerText.

I guess I'm just confused by some Javascript history.

like image 947
RobertAKARobin Avatar asked Apr 25 '15 14:04

RobertAKARobin


1 Answers

Well, the thing is, things like .innerHTML and .getElementById aren't really JavaScript objects at all. They're what the language specification calls "Host Objects" - it's a form of FFI. What happens when you call .getElementById in most browsers is that the string is marshalled from a JS string to a DOM string and then passed to C++ code.

In fact, they're allowed to have pretty much whatever semantics they please - the language makes no guarantees about how they act (this is also true for other DOM objects like timers and XHR).

like image 91
Benjamin Gruenbaum Avatar answered Oct 24 '22 22:10

Benjamin Gruenbaum