js dom[] code example
Example 1: HTML DOM
var myData = [{user: "James", address: "123 Keele St. Toronto, ON.", email:"[email protected]"},
{user: "Mary", address: "92 Appleby Ave. Hamilton, ON.", email:"[email protected]"},
{user: "Paul", address: "70 The Pond Rd. North Youk, ON.", email:"[email protected]"},
{user: "Catherine", address: "1121 New St. Burlington, ON.", email:"[email protected]"}];
window.onload = function() {
document.querySelector("#button1").onclick = generateTable;
}
function generateTable(){
var tbl = document.querySelector("#outputTable");
var tblExistingBody = tbl.querySelector("tbody");
if (tblExistingBody) tbl.removeChild(tblExistingBody);
var tblBody = document.createElement("tbody");
for (var i = 0; i < myData.length; i++) {
var row = document.createElement("tr");
row.appendChild(getTdElement(myData[i].user));
row.appendChild(getTdElement(myData[i].address));
row.appendChild(getTdLinkElement(myData[i].email, myData[i].email));
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
}
function getTdElement(text) {
var cell = document.createElement("td");
var cellText = document.createTextNode(text);
cell.appendChild(cellText);
return cell;
}
function getTdLinkElement(text, href) {
var anchor = document.createElement("a");
anchor.setAttribute("href", "mailto:"+href);
var anchorText = document.createTextNode(text);
anchor.appendChild(anchorText);
var cell = document.createElement("td");
cell.appendChild(anchor);
return cell;
}
Example 2: Html dom
<!-- USING EVENT HANDLER FOR DOM HTML -->
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>WEB222</title>
<style>
body { margin: 0 18%; }
</style>
<script>
window.onload = function() {
var elem = document.querySelector("#myBtn");
elem.addEventListener( "click", displayDate );
}
function displayDate() {
document.querySelector("#demo").innerHTML = (new Date()).toLocaleString();
}
</script>
</head>
<body>
<h1>WEB222 - HTML DOM Event</h1>
<p>Click "Show Current Time" to execute the displayDate() function.</p>
<p id="demo"></p>
<button id="myBtn">Show Current Time</button>
<br>
<!-- for downloading source files -->
<p><a href="" Download>Download</a></p>
</body>
</html>