In: Computer Science
use VISUAL STUDIO CODE to write this javascript program
Exercise 1
(a) Create a HTML file that uses createElement and appendChild to dynamically insert three paragraphs when a button is clicked.
(b) Create a HTML file that includes JavaScript that is similar to: let recs = [“my item …1”,”my item…2”, …] i.e. an array that contains several CSV item records. When the user clicks a button, each array element will be rendered as a list element. Use a HTML list. Use createElement and appendChild.
(c) Redo your createTable code from last week’s lab so that it uses createElement and appendChild rather than setting an innerHTML property.
a) HTML Code:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var para1 = document.createElement("p");
var para2 = document.createElement("p");
var para3 = document.createElement("p");
var para1Text = document.createTextNode("www.google.com");
var para2Text = document.createTextNode("www.microsoft.com");
var para3Text = document.createTextNode("www.adobe.com");
para1.appendChild(para1Text);
para2.appendChild(para2Text);
para3.appendChild(para3Text);
document.body.appendChild(para1);
document.body.appendChild(para2);
document.body.appendChild(para3);
}
</script>
</body>
</html>
Output:
***************************************************************************************************************
b) HTML Code:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<ul id="myList">
</ul>
<script>
function myFunction() {
let recs = ["my item…1","my item…2","my item…3","my
item…4","my item…5"]
recs.forEach(createListItem);
}
function createListItem(value, index, array) {
var node = document.createElement("LI");
var textnode = document.createTextNode(value);
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
}
</script>
</body>
</html>
Output:
***************************************************************************************************************
c) HTML Code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x = document.createElement("TABLE");
x.setAttribute("id", "myTable");
document.body.appendChild(x);
var y = document.createElement("TR");
y.setAttribute("id", "myTr");
document.getElementById("myTable").appendChild(y);
var z = document.createElement("TD");
var t = document.createTextNode("cell");
z.appendChild(t);
document.getElementById("myTr").appendChild(z);
}
</script>
</body>
</html>
Output: