Title
DOM Enlightenment - Exploring the relationship between JavaScript and the modern HTML DOM
Go Home
Category
Description
Exploring the relationship between JavaScript and the modern HTML DOM
Address
Phone Number
+1 609-831-2326 (US) | Message me
Site Icon
DOM Enlightenment - Exploring the relationship between JavaScript and the modern HTML DOM
Tags
Page Views
0
Share
Update Time
2022-05-04 20:55:00

"I love DOM Enlightenment - Exploring the relationship between JavaScript and the modern HTML DOM"

www.domenlightenment.com VS www.gqak.com

2022-05-04 20:55:00

You might also like: JavaScript EnlightenmentAn O'Reilly edited version (printed, epub, mobi, pdf) of this book is now avaliable from O'Reilly or AmazonWarning! This is the free online version of the DOM Enlightenment book in its pre-edited/draft form.DOM EnlightenmentExploring the relationship between JavaScript and the modern HTML DOMBy Cody Lindley Version: 0.6.0TweetForewordI make websites. Sometimes I make music. Over the years, I’ve noticed an interestingpattern of behavior from some musicians—often self-taught—who think of themselvesas creative types: they display an aversion to learning any music theory. The logic, theysay, is that knowing the theory behind music will somehow constrain their creativeabilities. I’ve never understood that logic (and I secretly believe that it’s a retroactiveexcuse for a lack of discipline). To my mind, I just don’t see how any kind of knowledgeor enlightenment could be a bad thing.Alas, I have seen the same kind of logic at work in the world of web design. There aredesigners who not only don’t know how to write markup and CSS, they actively refuseto learn. Again, they cite the fear of somehow being constrained by this knowledge (andagain, I believe that’s a self-justifying excuse).In the world of front-end development, that attitude is fortunately far less prevalent.Most web devs understand that there’s always more to learn. But even amongst developerswho have an encyclopediac knowledge of HTML and CSS, there is often a knowledgegap when it comes to the Document Object Model. That’s understandable. Youdon’t need to understand the inner workings of the DOM if you’re using a library likejQuery. The whole point of JavaScript libraries is to abstract away the browser’s internalAPI and provide a different, better API instead.Nonetheless, I think that many front-end devs have a feeling that they should knowwhat’s going on under the hood. That’s the natural reaction of a good geek when presentedwith a system they’re expected to work with. Now, thanks to DOM Enlightenment,they can scratch that natural itch.Douglas Crockford gave us a map to understand the inner workings of the JavaScriptlanguage in his book JavaScript: The Good Parts. Now Cody Lindley has given us thecorresponding map for the Document Object Model. Armed with this map, you’ll gainthe knowledge required to navigate the passageways and tunnels of the DOM.ixYou might not end up using this knowledge in every project. You might decide to use alibrary like jQuery instead. But now it will be your decision. Instead of having to use alibrary because that’s all that you know, you can choose if and when to use a library.That’s a very empowering feeling. That’s what knowledge provides. That is true enlightenment.—Jeremy Keith, founder and technical director of clearleft.com, and author ofDOM Scripting: Web Design with JavaScript and the Document Object ModelIntroductionThis book is not an exhaustive reference on DOM scripting or JavaScript. It may, however, be the most exhaustive book written about DOM scripting without the use of a library/framework. The lack of authorship around this topic is not without good reason. Most technical authors are not willing to wrangle this topic because of the differences that exist among legacy browsers and their implementations of the DOM specifications (or lack thereof).For the purpose of this book (i.e. grokking the concepts), I'm going to sidestep the browser API mess and dying browser discrepancies in an effort to expose the modern DOM. That's right, I'm going to sidestep the ugliness in an effort to focus on the here and now. After all, we have solutions like jQuery to deal with all that browser ugliness, and you should definitely be leveraging something like jQuery when dealing with deprecated browsers. While I am not promoting the idea of only going native when it comes to DOM scripting, I did write this book in part so that developers may realize that DOM libraries are not always required when scripting the DOM. I also wrote for the lucky few who get to write JavaScript code for a single environment (i.e. one browser, mobile browsers, or HTML+CSS+JavaScript-to-native via something like PhoneGap). What you learn in this book may just make a DOM library unnecessary in ideal situations, say for example, some light DOM scripting for deployment on a Webkit mobile browser only.Who should read this book As I authored this book, I specifically had two types of developers in mind. I assume both types already have an intermediate to advanced knowledge of JavaScript, HTML, and CSS. The first developer is someone who has a good handle on JavaScript or jQuery, but has really never taken the time to understand the purpose and value of a library like jQuery (the reason for its rhyme, if you will). Equipped with the knowledge from this book, that developer should fully be able to understand the value provided by jQuery for scripting the DOM. And not just the value, but how jQuery abstracts the DOM and where and why jQuery is filling the gaps. The second type of developer is an engineer who is tasked with scripting HTML documents that will only run in modern browsers or that will get ported to native code for multiple OS's and device distributions (e.g. PhoneGap) and needs to avoid the overhead (i.e. size or size v.s. use) of a library.Technical intentions, allowances, & limitationsThe content and code contained in this book was written with modern (IE9+, Firefox latest, Chrome latest, Safari latest, Opera latest) browsers in mind. It was my goal to only include concepts and code that are native to modern browsers. If I venture outside of this goal I will bring this fact to the readers attention. I've generally steered away from including anything in this book that is browser specific or implemented in a minority of the modern browsers.I'm not attempting in this book to dogmatically focus on a specific DOM, CSS, or HTML specification. Its not my goal here to dogmatically represent a specific specification. This would be too large of an undertaking (with little value IMO) given the number of specifications at work and the history/status of browsers correctly implementing the specifications. I have leverage and balanced in a very subjective manner the content from several specifications (Document Object Model (DOM) Level 3 Core Specification, DOM4, Document Object Model HTML , Element Traversal Specification, Selectors API Level 2, DOM Parsing and Serialization, HTML 5 Reference, HTML 5 - A vocabulary and associated APIs for HTML and XHTML, HTML Living Standard, HTML 5 - A technical specification for Web Developers, DOMLiving Standard). The content for this book is based more on where the community is and less on dogmatically attempting to express a specific spec.I'm covering several hand picked topics that are not DOM specific. I've included these topics in this book to help the reader build a proper understanding of the DOM in relationship to CSS and JavaScript.I've purposely left out any details as it pertains to XML or XHTML.I've purposely excluded the form and table api's to keep the book small. But I can see these sections being added in the future.LicenseThe DOM Enlightenment HTML version is released under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 unported license.Hard Copy & eBookO'Reilly will release and sell a hard copy & eBook in the near future.PrefaceBefore you begin, it is important to understand various styles employed in this book. Please do not skip this section, because it contains important information that will aid you in the unique styles of this book.This book is not like other programming booksThe enlightenment series (jQuery Enlightenment & JavaScript Enlightenment) is written in a style that favors small, isolated, immediately executable code over wordy explanations and monolithic programs. One of my favorite authors, C.S Lewis, asserts that words are the lowest form of communication that humans traffic in. I totally agree with this assertion and use it as the basis for the style of these books. I feel that technical information is best covered with as few words as possible, in conjunction with just the right amount of executable code and commenting required to express an idea. The style of this book attempts to present a clearly defined idea with as few words as possible, backed with real code. Because of this, when you first start grokking these concepts, you should execute and examine the code, thereby forming the foundation of a mental model for the words used to describe the concepts. Additionally, the format of these books attempts to systematically break ideas down into their smallest possible form and examine each one in an isolated context. All this to say that this is not a book with lengthy explanations or in-depth coverage on broad topics. Consider yourself warned. If it helps, think of it as a cookbook, but even more terse and to the point than usual.Color-coding conventionsIn the code examples (example shown below), orange is used to highlight code directly relevant to the concept being discussed. Any additional code used to support the orange colored code will be green. The color gray in the code examples is reserved for comments.live code: http://jsfiddle.net/domenlightenment// this is a comment about a specific part of the codevar foo = 'calling out this part of the code'; jsFiddleThe majority of code examples in this book are linked to a corresponding jsFiddle page, where the code can be tweaked and executed online. The jsFiddle examples have been configured to use the Firebug lite-dev plugin to ensure the reader views the console.log prevalent in this book. Before reading this book, make sure you are comfortable with the usage and purpose of console.log.In situations where jsFiddle caused complications with the code example, I simply chose not to link to a live example.About the AuthorCody Lindley is a client-side engineer (aka front-end developer) and recovering Flash developer. He has an extensive background working professionally (11+ years) with HTML, CSS, JavaScript, Flash, and client-side performance techniques as it pertains to web development. If he is not wielding client-side code he is likely toying with interface/interaction design or authoring material and speaking at various conferences. When not sitting in front of a computer, it is a sure bet he is hanging out with his wife and kids in Boise, Idaho – training for triathlons, skiing, mountain biking, road biking, alpine climbing, reading, watching movies, or debating the rational evidence for a Christian worldview.Table of ContentsChapter 1 - Node Overview1.1 The Document Object Model (aka the DOM) is a hierarchy/tree of JavaScript node objectsWhen you write an HTML document you encapsulate HTML content inside ofother HTML content. By doing this you setup a hierarchy that can beexpressed as a tree.Often this hierarchy or encapsulation system is indicated visually by indentingmarkup in an HTML document. The browser when loading the HTML documentinterrupts and parsesthis hierarchy to create a tree of node objects that simulates howthe markup is encapsulated. HTMLThe above HTML code when parsed by a browser creates a document that contains nodes structrured in a tree format (i.e. DOM). BelowI reveal the tree struture from the above HTML document using Opera's Dragonfly DOM inspector. On the left you see the HTML document in its tree form. And on the right you see the corresponding JavaScript object that represents the selected element on the left. For example, the selected element highlighted in blue,is an element node and an instance of the HTMLBodyElement interface.What you should take away here is that html documents get parsed by a browser and converted into a tree structure of node objects representing a live document. The purpose of the DOM is to provide a programatic interface for scripting (removing, adding, replacing, eventing, modifiying) this live document using JavaScript. Notes The DOM originally was an application programming interface for XML documents that has been extended for use in HTML documents.1.2 Node object typesThe most common (I'm not highlighting all of them in the list below) types of nodes (i.e. nodeType/node classifications) one encounters when working with HTML documents are listed below.DOCUMENT_NODE (e.g. window.document)ELEMENT_NODE (e.g. , , , , , , etc...)ATTRIBUTE_NODE (e.g. class="funEdges")TEXT_NODE (e.g. text characters in an html document including carriage returns and white space)DOCUMENT_FRAGMENT_NODE (e.g. document.createDocumentFragment())DOCUMENT_TYPE_NODE (e.g. ) I've listed the node types above formatted (all uppercase with _ separating words)exactly as the constant property is written in the JavaScript browser environment as a property of the Node object. These Node properties are constant valuesand are used to store numeric code values which map to a specific type ofnode object. For example in the following code example, Node.ELEMENT_NODE is equal to 1.And 1 is the code value used to identify element nodes.live code: http://jsfiddle.net/domenlightenment/BAVrsconsole.log(Node.ELEMENT_NODE) //logs 1, one is the numeric code value for element nodesIn the code belowI log all of the node types and there values.live code: http://jsfiddle.net/domenlightenment/YcXGDfor(var key in Node){ console.log(key,' = '+Node[key]); };/* the above code logs to the console the followingELEMENT_NODE = 1ATTRIBUTE_NODE = 2TEXT_NODE = 3CDATA_SECTION_NODE = 4ENTITY_REFERENCE_NODE = 5ENTITY_NODE = 6PROCESSING_INSTRUCTION_NODE = 7COMMENT_NODE = 8DOCUMENT_NODE = 9DOCUMENT_TYPE_NODE = 10DOCUMENT_FRAGMENT_NODE = 11NOTATION_NODE = 12DOCUMENT_POSITION_DISCONNECTED = 1DOCUMENT_POSITION_PRECEDING = 2DOCUMENT_POSITION_FOLLOWING = 4DOCUMENT_POSITION_CONTAINS = 8DOCUMENT_POSITION_CONTAINED_BY = 16DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 32 */The previous code example gives an exhaustive list of all node types. For the purpose of this book I'll be discussing the shorter list of node types listed at the start of this section. These nodes willmost likely be the ones you come in contact with when scripting an HTML page. In the table below I list the name given to the interface/constructor thatinstantiates the most common node types and their corresponding nodeType classification by number and name. What I hope you take away from the table below is the nodeType value (i.e. 1) is just a numeric classificaiton used to describe a certain type of node constructed from a certain JavaScript interface/constructor. For example, the HTMLBodyElement interface reprsents a node object that has a node type of 1, which is a classification for ELEMENT_NODE's.NodeInterface/Constructor: nodeType (returned from .nodeType): HTML*Element,(e.g. HTMLBodyElement) 1 (i.e. ELEMENT_NODE)Text 3 (i.e. TEXT_NODE)Attr2 (i.e. ATTRIBUTE_NODE)HTMLDocument 9 (i.e. DOCUMENT_NODE)DocumentFragment 11 (i.e. DOCUMENT_FRAGMENT_NODE) DocumentType10 (i.e. DOCUMENT_TYPE_NODE)NotesThe DOM specification semantically labels nodes like Node, Element, Text, Attr, and HTMLAnchorElement as aninterface, which it is, but keep in mind its also the name given to the JavaScriptconstructor function that constructs the nodes. As you read this book Iwill be referring to these interfaces (i.e. Element, Text, Attr, HTMLAnchorElement) as objects or constructorfunctions while the specification refers to them as interfaces.The ATTRIBUTE_NODE is not actually part of a tree but listed for historical reasons. In this book I do not provide a chapter on attribute nodes and instead discuss them in the Element node chapter given that attributes nodes are sub-like nodes of element nodes with no particiipation in the actual DOM tree structure. Be aware the ATTRIBUTE_NODE is being depreciated in DOM 4.I've not included detail in this book on the COMMENT_NODE but you should be aware that comments in an HTML document are Comment nodes and similar in nature to Text nodes. As I discuss nodes throughout the book I will rarely refer to aspecific node using its nodeType name (e.g. ELEMENT_NODE). This is done to be consistent withverbiage used in the specifications provided by the W3C & WHATWG. 1.3 Sub-node objects inherit from the Node objectEach node object in a typical DOM tree inherits properties and methods from Node. Depending upon the type of node in the document there are alsoadditional sub node object/interfaces that extend the Node object.Below I detail the inheritance model implemented by browsers for the mostcommon node interfaces (< indicates inherited from).Object