HTML | DOM Table Object
The Table object is used for representing an HTML <table> element. It can be used to create and access a table.
Syntax:
- To access table element.:
document.getElementById("id");
- To create a table object:
document.createElement("TABLE");
Below program illustrates the Table Object :
Example-1: Accessing a <table> element by using the getElementById() method.
<!DOCTYPE html> < html > < head > < title >Table Object in HTML</ title > < style > table, td { border: 1px solid green; } h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </ style > </ head > < body > < h1 >w3wiki</ h1 > < h2 >Table Object</ h2 > < br > < table id = "table" align = "center" > < tr > < td >Fork Python</ td > < td >Fork Java</ td > </ tr > < tr > < td >Sudo Placement</ td > < td >Fork CPP</ td > </ tr > </ table > < p >Double click the "Delete Row" button to remove the second row from the table.</ p > < button onclick = "delete()" >Delete Row</ button > < script > function delete() { // Accessing table object. var x = document.getElementById("table"); x.deleteRow(0); } </ script > </ body > </ html > |
Output:
Before Clicking The Button:
After Clicking The Button:
Example-2: Creating a <table> element by using the document.createElement() method.
<!DOCTYPE html> < html > < head > < title >Table Object in HTML</ title > < style > table { border: 1px solid green; } h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </ style > </ head > < body > < h1 >w3wiki</ h1 > < h2 >Table Object</ h2 > < br > < p >Double click the "Create" button to create a TABLE, a Table row and a Table cell element.</ p > < button ondblclick = "create()" >Create</ button > < script > function create() { // Create table object. var a = document.createElement("TABLE"); a.setAttribute("id", "MyTable"); document.body.appendChild(a); var b = document.createElement("TR"); b.setAttribute("id", "MyTr"); document.getElementById("MyTable").appendChild(b); var c = document.createElement("TD"); var d = document.createTextNode("Table cell"); c.appendChild(d); document.getElementById("MyTr").appendChild(c); } </ script > </ body > </ html > |
Output:
Before Clicking The Button:
After Clicking The Button:
Supported Browsers:
- Opera
- Internet Explorer
- Google Chrome
- Firefox
- Apple Safari