04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 10: The Document Object Model<br />

The function can be called as follows:<br />

loadStyleString(“body{background-color:red}”);<br />

Styles specified in this way are added to the page instantly, so changes should be seen immediately.<br />

If you ’ re coding for IE specifically, be careful using styleSheet.cssText . If<br />

you reuse the same < style > element and try to set this property more than<br />

once, it has a tendency to crash the browser. This is a bug in the browser that<br />

hopefully will be fixed in the future.<br />

Manipulating Tables<br />

One of the most complex structures in HTML is the < table > element. Creating new tables typically<br />

means numerous tags for table rows, table cells, table headers, and so forth. Due to this complexity,<br />

using the core DOM methods to create and change tables can require a large amount of code. Suppose<br />

you want to create the following HTML table using the DOM:<br />

< table border=”1” width=”100%” ><br />

< tbody ><br />

< tr ><br />

< td > Cell 1,1 < /td ><br />

< td > Cell 2,1 < /td ><br />

< /tr ><br />

< tr ><br />

< td > Cell 1,2 < /td ><br />

< td > Cell 2,2 < /td ><br />

< /tr ><br />

< /tbody ><br />

< /table ><br />

To accomplish this with the core DOM methods, the code would look something like this:<br />

//create the table<br />

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

table.border = 1;<br />

table.width = “100%”;<br />

//create the tbody<br />

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

table.appendChild(tbody);<br />

//create the first row<br />

var row1 = document.createElement(“tr”);<br />

tbody.appendChild(row1);<br />

var cell1_1 = document.createElement(“td”);<br />

cell1_1.appendChild(document.createTextNode(“Cell 1,1”));<br />

row1.appendChild(cell1_1);<br />

var cell2_1 = document.createElement(“td”);<br />

cell2_1.appendChild(document.createTextNode(“Cell 2,1”));<br />

311

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

Saved successfully!

Ooh no, something went wrong!