使用Javascript和DOM Interfaces来处理HTML

所属分类: 网络编程 / JavaScript 阅读数: 456
收藏 0 赞 0 分享
1、创建表格

[Ctrl+A 全选 注:引入外部Js需再刷新一下页面才能执行]

Note the order in which we created the elements and the text node: 

First we created the TABLE element. 
Next, we created the TBODY element, which is a child of the TABLE element. 
Next, we used a loop to create the TR elements, which are children of the TBODY element. 
For each TR element, we used a loop to create the TD elements, which are children of TR elements. 
For each TD element, we then created the text node with the table cell's text. 
Once we have created the TABLE, TBODY, TR, and TD elements and then the text node, we then append each object to its parent in the opposite order: 



First, we attach each text node to its parent TD element using 
mycurrent_cell.appendChild(currenttext);
Next, we attach each TD element to its parent TR element using 
mycurrent_row.appendChild(mycurrent_cell);
Next, we attach each TR element to the parent TBODY element using 
mytablebody.appendChild(mycurrent_row);
Next, we attach the TBODY element to its parent TABLE element using 
mytable.appendChild(mytablebody);
Next, we attach the TABLE element to its parent BODY element using 
mybody.appendChild(mytable);


Remember this technique. You will use it frequently in programming for the W3C DOM. First, you create elements from the top down; then you attach the children to the parents from the bottom up. 

Here's the HTML markup generated by the JavaScript code: 

...
<TABLE border=5>
<tr><td>cell is row 0 column 0</td><td>cell is row 0 column 1</td></tr>
<tr><td>cell is row 1 column 0</td><td>cell is row 1 column 1</td></tr>
</TABLE>
...

Here's the DOM object tree generated by the code for the TABLE element and its child elements: 

Image:sample1-tabledom.jpg 

You can build this table and its internal child elements by using just a few DOM methods. Remember to keep in mind the tree model for the structures you are planning to create; this will make it easier to write the necessary code. In the TABLE tree of Figure 1 the element TABLE has one child, the element TBODY. TBODY has two children. Each TBODY's child (TR) has one child (TD). Finally, each TD has one child, a text node. 


2、

[Ctrl+A 全选 注:引入外部Js需再刷新一下页面才能执行]

In this example, we set the myP variable to the DOM object for the second p element inside the body: 



First, we get a list of all the body elements via 
document.getElementsByTagName("body")
Since there is only one body element in any valid HTML document, this list will have only one item. 
Next, we get the first element on that list, which will be the object for the body element itself, via 
myBody=myDocumentElements.item(0);
Next, we get all the p elements that are children of the body via 
myBodyElements=myBody.getElementsByTagName("p");
Finally, we get the second item from the list of p elements via 
myP=myBodyElements.item(1);


Image:sample2a2.jpg 

Once you have gotten the DOM object for an HTML element, you can set its properties. For example, if you want to set the style background color property, you just add: 

myP.style.background="rgb(255,0,0)";
// setting inline STYLE attribute


[编辑]

Creating TextNodes with document.createTextNode(..) 
Use the document object to invoke the createTextNode method and create your text node. You just need to pass the text content. The return value is an object that represents the text node. 

myTextNode=document.createTextNode("world");

This means that you have created a node of the type TEXT_NODE (a piece of text) whose text data is "world", and myTextNode is your reference to this node object. To insert this text into your HTML page, you need to make this text node a child of some other node element. 



[编辑]

Inserting Elements with appendChild(..) 
So, by calling myP.appendChild([node_element]), you are making the element a new child of the second P element. 

myP.appendChild(myTextNode);

After testing this sample, note that the words hello and world are together: helloworld. So visually, when you see the HTML page it seems like the two text nodes hello and world are a single node, but remember that in the document model, there are two nodes. The second node is a new node of type TEXT_NODE, and it is the second child of the second P tag. The following figure shows the recently created Text Node object inside the document tree. 

Image:sample2b2.jpg 

createTextNode and appendChild is a simple way to include white space between the words hello and world. Another important note is that the appendChild method will append the child after the last child, just like the word world has been added after the word hello. So if you want to append a Text Node between hello and world you will need to use insertBefore instead of appendChild.


[编辑]

Creating New Elements with the document object and the createElement(..) method 
You can create new HTML elements or any other element you want with createElement. For example, if you want to create a new P element as a child of the BODY element, you can use the myBody in the previous example and append a new element node. To create a node simply call document.createElement("tagname"). For example: 

myNewPTAGnode=document.createElement("p");
myBody.appendChild(myNewPTAGnode);

Image:sample2c.jpg 



[编辑]

Removing nodes with the removeChild(..) method 
Each node can be removed. The following line removes the text node which contains the word world of the myP (second P element). 

myP.removeChild(myTextNode);

Finally you can add myTextNode (which contains the word world) into the recently created P element: 

myNewPTAGnode.appendChild(myTextNode);

The final state for the modified object tree looks like this: 

Image:sample2d.jpg 



[编辑]

Creating a table dynamically (back to Sample1.html) 
For the rest of this article we will continue working with sample1.html. The following figure shows the table object tree structure for the table created in the sample. 



[编辑]

Reviewing the HTML Table structure 
Image:sample1-tabledom.jpg 



[编辑]

Creating element nodes and inserting them into the document tree 
The basic steps to create the table in sample1.html are: 

Get the body object (first item of the document object). 
Create all the elements. 
Finally, append each child according to the table structure (as in the above figure). The following source code is a commented version for the sample1.html. 
At the end of the start function there is a new line of code. The table's border property was set using another DOM method, setAttribute. setAttribute has two arguments: the attribute name and the attribute value. You can set any attribute of any element using the setAttribute method.
<head>
<title>Sample code - Traversing an HTML Table with JavaScript and DOM Interfaces</title>
<script>
  function start() {
    // get the reference for the body
    var mybody=document.getElementsByTagName("body").item(0);
    // creates an element whose tag name is TABLE
    mytable = document.createElement("TABLE");
    // creates an element whose tag name is TBODY
    mytablebody = document.createElement("TBODY");
    // creating all cells
    for(j=0;j<2;j++) {
      // creates an element whose tag name is TR
      mycurrent_row=document.createElement("TR");
      for(i=0;i<2;i++) {
        // creates an element whose tag name is TD
        mycurrent_cell=document.createElement("TD");
        // creates a Text Node
        currenttext=document.createTextNode("cell is row "+j+", column "+i);
        // appends the Text Node we created into the cell TD
        mycurrent_cell.appendChild(currenttext);
        // appends the cell TD into the row TR
        mycurrent_row.appendChild(mycurrent_cell);
      }
      // appends the row TR into TBODY
      mytablebody.appendChild(mycurrent_row);
    }
    // appends TBODY into TABLE
    mytable.appendChild(mytablebody);
    // appends TABLE into BODY
    mybody.appendChild(mytable);
    // sets the border attribute of mytable to 2;
    mytable.setAttribute("border","2");
  }
</script>
</head>
<body onload="start()">
</body>
</html>



[编辑]

Manipulating the table with DOM and CSS 


[编辑]

Getting a text node from the table 
This example introduces two new DOM attributes. First it uses the childNodes attribute to get the list of child nodes of mycel. The childNodes list includes all child nodes, regardless of what their name or type is. Like getElementsByTagName, it returns a list of nodes. The difference is that getElementsByTagName only returns elements of the specified tag name. Once you have the returned list, use item(x) method to retrieve the desired child item. This example stores in myceltext the text node of the second cell in the second row of the table. Then, to display the results in this example, it creates a new text node whose content is the data of myceltext and appends it as a child of the BODY element. 

If your object is a text node, you can use the data attribute and retrieve the text content of the node.
mybody=document.getElementsByTagName("body").item(0);
mytable=mybody.getElementsByTagName("table").item(0);
mytablebody=mytable.getElementsByTagName("tbody").item(0);
myrow=mytablebody.getElementsByTagName("tr").item(1);
mycel=myrow.getElementsByTagName("td").item(1);
// first item element of the childNodes list of mycel
myceltext=mycel.childNodes.item(0);
// content of currenttext is the data content of myceltext
currenttext=document.createTextNode(myceltext.data);
mybody.appendChild(currenttext);



[编辑]

Getting an attribute value 
At the end of sample1 there is a call to setAttribute on the mytable object. This call was used to set the border property of the table. To retrieve the value of the attribute, use the getAttribute method: 

mytable.getAttribute("border");



[编辑]

Hiding a column by changing style properties 
Once you have the object in your JavaScript variable, you can set style properties directly. The following code is a modified version of sample1.html in which each cell of the second column is hidden and each cell of the first column is changed to have a red background. Note that the style property was set directly. 

<html>
<body onload="start()">
</body>
<script>
  function start() {
    var mybody=document.getElementsByTagName("body").item(0);
    mytable = document.createElement("TABLE");
    mytablebody = document.createElement("TBODY");
    for(j=0;j<2;j++) {
      mycurrent_row=document.createElement("TR");
      for(i=0;i<2;i++) {
        mycurrent_cell=document.createElement("TD");
        currenttext=document.createTextNode("cell is:"+i+j);
        mycurrent_cell.appendChild(currenttext);
        mycurrent_row.appendChild(mycurrent_cell);
        // set the cell background color
        // if the column is 0. If the column is 1 hide the cel
        if(i==0) {
          mycurrent_cell.style.background="rgb(255,0,0)";
        } else {
          mycurrent_cell.style.display="none";
        }
      }
      mytablebody.appendChild(mycurrent_row);
    }
    mytable.appendChild(mytablebody);
    mybody.appendChild(mytable);
  }
</script>
</html>

取自"http://developer.mozilla.org/cn/docs/%E4%BD%BF%E7%94%A8Javascript%E5%92%8CDOM_Interfaces%E6%9D%A5%E5%A4%84%E7%90%86HTML"

页面分类: DOM
更多精彩内容其他人还在看

Angular使用Md5加密的解决方法

这篇文章主要介绍了Angular使用Md5加密的解决方法,需要的朋友可以参考下
收藏 0 赞 0 分享

详解JS构造函数中this和return

本文通过实例代码给大家介绍了JS构造函数中this和return,需要的朋友参考下吧
收藏 0 赞 0 分享

ES6中Array.find()和findIndex()函数的用法详解

ES6为Array增加了find(),findIndex函数。find()函数用来查找目标元素,找到就返回该元素,找不到返回undefined,而findIndex()函数也是查找目标元素,找到就返回元素的位置,找不到就返回-1。下面通过实例详解,需要的朋友参考下吧
收藏 0 赞 0 分享

JS闭包的几种常见形式实例详解

本文通过实例代码给大家详细介绍了js闭包的几种常见形式,代码简单易懂,非常不错,具有参考借鉴价值,需要的朋友参考下
收藏 0 赞 0 分享

ES6中Array.copyWithin()函数的用法实例详解

ES6为Array增加了copyWithin函数,用于操作当前数组自身,用来把某些个位置的元素复制并覆盖到其他位置上去。下面重点给大家介绍ES6中Array.copyWithin()函数的用法,需要的朋友参考下
收藏 0 赞 0 分享

Javascript 严格模式use strict详解

严格模式:由ECMA-262规范定义的JavaScript标准,对javascrip的限制更强。这篇文章主要介绍了Javascript 严格模式use strict详解 ,需要的朋友可以参考下
收藏 0 赞 0 分享

引入JavaScript时alert弹出框显示中文乱码问题

今天在HTML中引入JavaScript文件运行时,alert弹出的提示框中文显示为乱码,怎么解决此问题呢?下面小编给大家带来了引入JavaScript时alert弹出框显示中文乱码问题的解决方法,一起看看吧
收藏 0 赞 0 分享

AngularJs 延时器、计时器实例代码

这篇文章主要介绍了AngularJs 延时器、计时器实例代码,需要的朋友可以参考下
收藏 0 赞 0 分享

JS分页的实现(同步与异步)

这篇文章主要介绍了JS分页的实现(同步与异步),需要的朋友可以参考下
收藏 0 赞 0 分享

Angularjs自定义指令实现分页插件(DEMO)

由于最近的一个项目使用的是angularjs1.0的版本,涉及到分页查询数据的功能,后来自己就用自定义指令实现了该功能,下面小编把实例demo分享到脚本之家平台,需要的朋友参考下
收藏 0 赞 0 分享
查看更多