Home >Web Front-end >JS Tutorial >Organize common JavaScript operations on various types of elements in DOM_Basic knowledge
Node type
nodeType
The following are some important nodeType values:
1: element element
2: Attribute attr
3: Text text
8: Comments
9: Document document
nodeName,nodeValue
Node relationship
childNodes: Each node has a childNodes attribute, which stores a NodeList object
firstChild: equivalent to childNodes[0]
lastChild: equivalent to childNodes.length-1
At the same time, other nodes in the same list can be accessed by using the previousSibling and nextSibling properties of each node in the list.
Operation Node
appendChild()
The appendChild() method is used to add a node to the end of the childNodes list. After adding a node, the relationship pointers of the new node, parent node and previous last child node of childNodes will be updated accordingly.
insertBefore()
insertBefore() This method accepts two parameters: the node to be inserted and the node used as a reference.
// 插入后成为最后一个子节点 returnedNode = someNode.insertBefore(newNode,null); // 插入后成为第一个节点 returnedNode = someNode.insertBefore(newNode,someNode.firstChild); // 插入到最后一个子节点前面 returnedNode = someNode.insertBefore(newNode,someNode.lastChild);
repaceChild()
repaceChild() accepts two parameters, the node to be inserted and the node to be replaced
var returnedNode = someNode.replaceChild(newNode,someNode.firstChild);
removeChild()
Only remove nodes, not replace them.
var formerFirstChild = someNode.removeChild(someNode.firstChild);
cloneNode()
item 1
item 2
item 3
var deepList = myList.cloneNode(true); console.log(deepList.length); // 3 var shallowList = myList.cloneNode(false); console.log(shallowList.childNodes.length); //0
Document type
Document node has the following characteristics:
Child node of document
var html = document.documentElement; // 取得对<html>的引用 console.log(html === document.childNodes[0]); // true console.log(html === document.firstChild); // true
Document information
// 取得文档的标题 var originalTitle = document.title; // 设置文档标题 document.title = "New page title"; // 取得完整的url var url = document.URL; // 取得域名 var domain = document.domain; // 取得来源页面的url var referrer = document.referrer; //假设页面来自p2p.wrox.com域 document.domain = "wrox.com"; // 成功 document.domain = "nczonline.net"; // 失败
Calling document.getElementById("myElement"); in IE7 will return the d5fd7aea971a85678ba271703566ebfd element as shown below;
The best way is not to make the name attribute of the form field the same as the ID of other elements.
<input type="text" name="myElement" value="text field"> <div id="myElement">a div</div>
Special Collection
Document writing
<html> <head> <title>document.write() Example 3</title> </head> <body> <script type="text/javascript"> document.write("<script type=\"text/javascript\" src=\"file.js\">") + "<\/script>"); </script> </body> </html>
The string 2cacc6d41bbb37262a98f745aa00fbf0 will not be used as the closing tag of the external script tag, so there will be no redundant content on the page.
Element type
Element node has the following characteristics:
To access the tag name of an element, you can use the nodeName attribute or the tagName attribute;
<div id="myDiv"></div> var div = document.getElementById("myDiv"); console.log(div.tagName); // DIV console.log(div.nodeName); // DIV if (element.tagName=="div") { // 不能这样比较,很容易出错 } if (element.tagName.toLowerCase =="div") { // 这样最好(适用于任何文档) }
Acquire characteristics
There are three main DOM methods for operating attributes, namely getAttribute(), setAttribute(), and removeAttribute();
Note that the attribute name passed to getAttribute() is the same as the actual attribute name. It seems that if you want to get the attribute value of class, you should pass in "class" instead of "className".
var div = document.getElementById("myDiv"); console.log(div.getAttribute("class")); // bd
Create element
New elements can be created using the document.createElement() method.
Child node of element
Before performing an operation, it is usually necessary to check the nodeType attribute first, as shown in the following example:
for (var i=0; len = element.childNodes.length; i<len; i++){ if (element.childNodes[i].nodeType ==1) { // 执行某些操作 } }
Text类型
Text节点具有以下特征:
创建文本节点
可以使用document.createTextNode()创建新文本节点。
规范化文本节点
normalize()
分割文本节点
splitText()
Comment类型
comment节点具有下列特征:
DOM操作技术
操作表格
// 创建 table var table = document.createElement("table"); table.border = 1; table.width = "100%"; // 创建tbody var tbody = document.createElement("tbody"); table.appendChild(tbody); // 创建第一行 tbody.insertRow(0); tbody.rows[0].insertCell(0); tbody.rows[0].cells[0].appendChild(document.createTextNode("cell 1,1")); tbody.rows[0].insertCell(1); tbody.rows[0].cells[1].appendChild(document.createTextNode("cell 2,1")); // 创建第二行 tbody.insertRow(01); tbody.rows[1].insertCell(0); tbody.rows[1].cells[0].appendChild(document.createTextNode("cell 1,2")); tbody.rows[1].insertCell(1); tbody.rows[1].cells[1].appendChild(document.createTextNode("cell 2,2")); document.body.appendChild(table);
选择符API
querySelector()方法
// 取得body元素 var tbody = document.querySelector('body'); // 取得ID为"myDIV"的元素 var myDIV = document.querySelector("#myDiv"); // 取得类为"selected"的第一个元素 var selected = document.querySelector(".selected"); // 取得类为"button"的第一个图像元素 var img = document.body.querySelector("img.button");
querySelectorAll()方法
// 取得某<div>中的所有<em>元素(类似于getElementsByTagName("em")) var ems = document.getElementById("myDiv").querySelectorAll("em"); // 取得类为"selected"的所有元素 var selecteds = document.querySelectorAll(".selected"); // 取得所有<p>元素中的所有<strong>元素 var strongs = document.querySelectorAll("p strong");
HTML5
与类相关的扩充
getElementsByClassName()方法:
该方法可以通过document对象及所有HTML元素调用该方法。
// 取得所有类中包含"username"和"current"的元素。类名的先后顺序无所谓 var allCurrentUsernames = document.getElementsByClassName("username current"); // 取得ID为"myDiv"的元素中带有类名"selected"的所有元素 var selected = document.getElementById("myDiv").getElementsByClassName("selected");
焦点管理
HTML5也添加了辅助管理DOM焦点的功能。首先就是document.activeElement属性,这个属性始终会引用DOM中当前获得了焦点的元素。
var button = document.getElementById("myButton"); button.focus(); alert(document.activeElement === button); // true
默认情况下,文档刚刚加载完成时,document.activeElement中保存的是document.body元素的引用。文档加载期间,docuemnt.activeElement的值为null。
另外就是新增了document.hasFocus()方法,这个方法用于确定文档是否获得了焦点。
var button = document.getElementById("myButton"); botton.focus(); alert(document.hasFocus()); // true