document
document
The document object represents the current page. Since HTML is represented as a tree structure in the form of DOM in the browser, the document object is the root node of the entire DOM tree.
The title attribute of document is read from <title>xxx</title> in the HTML document, but it can be changed dynamically:
<html> <head> <script> 'use strict'; document.title = '努力学习JavaScript!'; </script> </head> <body> </body> </html>
Please observe the change of the browser window title.
To find a node in the DOM tree, you need to start searching from the document object. The most commonly used searches are based on ID and Tag Name.
We first prepare the HTML data:
<dl id="drink-menu" style="border:solid 1px #ccc;padding:6px;"> <dt>摩卡</dt> <dd>热摩卡咖啡</dd> <dt>酸奶</dt> <dd>北京老酸奶</dd> <dt>果汁</dt> <dd>鲜榨苹果汁</dd> </dl>
Use getElementById() and getElementsByTagName() provided by the document object to obtain a DOM node by ID and a group of DOM nodes by Tag name:
'use strict'; var menu = document.getElementById('drink-menu'); var drinks = document.getElementsByTagName('dt'); var i, s, menu, drinks; menu = document.getElementById('drink-menu'); menu.tagName; // 'DL' drinks = document.getElementsByTagName('dt'); s = '提供的饮料有:'; for (i=0; i<drinks.length; i++) { s = s + drinks[i].innerHTML + ','; } alert(s);
Mocha
Hot Mocha Coffee
Yoghurt
##Beijing Old yogurt
Juice
Freshly squeezed apple juice<html> <head> <script> 'use strict'; var menu = document.getElementById('drink-menu'); var drinks = document.getElementsByTagName('dt'); var i, s, menu, drinks; menu = document.getElementById('drink-menu'); menu.tagName; // 'DL' drinks = document.getElementsByTagName('dt'); s = '提供的饮料有:'; for (i=0; i<drinks.length; i++) { s = s + drinks[i].innerHTML + ','; } alert(s); </script> </head> <body> <dl id="drink-menu" style="border:solid 1px #ccc;padding:6px;"> <dt>摩卡</dt> <dd>热摩卡咖啡</dd> <dt>酸奶</dt> <dd>北京老酸奶</dd> <dt>果汁</dt> <dd>鲜榨苹果汁</dd> </dl> </body> </html>