18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

DOM Basics<br />

❑<br />

❑<br />

❑<br />

deleteCaption() — deletes the element<br />

deleteRow(position) — deletes the row in the given position<br />

insertRow(position) — inserts a row in the given position in the rows collection<br />

The element adds the following:<br />

❑<br />

❑<br />

❑<br />

rows — collection of rows in the element<br />

deleteRow(position) — deletes the row in the given position<br />

insertRow(position) — inserts a row in the given position in the rows collection<br />

The element adds the following:<br />

❑<br />

❑<br />

❑<br />

cells — collection of cells in the element<br />

deleteCell(position) — deletes the cell in the given position<br />

insertCell(position) — inserts a cell in the given position in the cells collection<br />

What does all of this mean? Essentially, it means that creating a table can be a lot less complicated if you<br />

use these convenient properties and methods:<br />

//create the table<br />

var oTable = document.createElement(“table”);<br />

oTable.setAttribute(“border”, “1”);<br />

oTable.setAttribute(“width”, “100%”);<br />

//create the tbody<br />

var oTBody = document.createElement(“tbody”);<br />

oTable.appendChild(oTBody);<br />

//create the first row<br />

oTBody.insertRow(0);<br />

oTBody.rows[0].insertCell(0);<br />

oTBody.rows[0].cells[0].appendChild(document.createTextNode(“Cell 1,1”));<br />

oTBody.rows[0].insertCell(1);<br />

oTBody.rows[0].cells[1].appendChild(document.createTextNode(“Cell 2,1”));<br />

//create the second row<br />

oTBody.insertRow(1);<br />

oTBody.rows[1].insertCell(0);<br />

oTBody.rows[1].cells[0].appendChild(document.createTextNode(“Cell 1,2”));<br />

oTBody.rows[1].insertCell(1);<br />

oTBody.rows[1].cells[1].appendChild(document.createTextNode(“Cell 2,2”));<br />

//add the table to the document body<br />

document.body.appendChild(oTable);<br />

In this code, the creation of the and elements remain the same. What has changed<br />

is the section creating the two rows, which now makes use of the HTML DOM Table properties and<br />

methods. To create the first row, the insertRow() method is called on the element with an<br />

argument of 0, which indicates the position in which the row should be placed. After that point, the row<br />

can be referenced by oTBody.rows[0] because it is automatically created and added into the <br />

element in position 0.<br />

181

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!