Summary
-
console.log
andconsole.dir
both output their arguments to the console for JavaScript objects, but for DOM elementsconsole.log(elem)
shows the element DOM tree whileconsole.dir(elem)
shows the element as a DOM object and is good to explore its properties -
Main DOM node properties are:
nodeType
shows whether a node is a text or an element node. It has a numeric value:1
for elements,3
for text nodes, and9
for document objectnodeName/tagName
means tag name (upper-cased unless XML-mode) for elements and for non-element nodesnodeName
describes what it is whiletagName
isundefined
innerHTML
is the HTML content of the element and can be modified. IfinnerHTML
inserts a<script>
tag into the document, it becomes a part of HTML, but doesn’t execute.innerHTML+=
does a full overwrite instead of additionouterHTML
is the full HTML of the element. A write operation intoelem.outerHTML
does not touchelem
itself. Instead it gets replaced with the new HTML in the outer contextnodeValue/data
is the content of a non-element node (text, comment) and usually the same. Can be modifiedtextContent
is the entire text inside the element. Writing into it puts the text inside the element, with all special characters and tags treated exactly as text. Can safely insert user-generated text and protect from unwanted HTML insertionshidden
does the same as CSSdisplay:none
when set totrue
-
Most standard HTML attributes have a corresponding DOM property but they are not always the same
Tasks
-
Count descendants
let lis = document.querySelectorAll("li"); for (let li of lis) { let title = li.firstChild.data; let numDescendants = li.querySelectorAll("li").length; console.log(title.trim() + ": " + numDescendants); }
-
What’s in the nodeType?
The last DOM node is exactly
<script>
at the time of<script>
execution so the result is1
-
Tag in comment
It shows
BODY
-
Where is the “document” in the hierarchy?
document
is an instance ofHTMLDocument
class.HTMLDocument
inherits fromDocument
andDocument
inherits fromNode
.