Practice Set, Week 8, Modifying the DOM, Problem 2

for CSCI E3, Harvard University author(s): Larry Bouthillier

by DustyWhite

HTML

<h3>Practice Set #2, Week 8, Modifying the DOM</h3>

<p>We're going to practice the steps of manually creating an adding a DOM element to a page. To do this, we'll create a DIV with id="myNewDiv" that contains some text, and attach it to the div already on this page with id="addNewOneHere". If you've done it right, it will appear with a red background.</p>
<p>Hint: There's five steps here, as shown in the lessons, particularly lesson 3 section 2, the TOC example in Video 8.6, and the <a href="http://javascript.info/tutorial/modifying-document#creating-elements" target="blank">readings on javascript.info</a>. You'll have to:
    <ol>
        <li>create a 'DIV' element node and assign it to a variable</li>
        <li>using setAttribute(), give it an ID attribute of "myNewDiv"</li>
        <li>create a text node with some text of your choosing, and assign it to a variable</li>
        <li>append you text node to your element</li>
        <li>append your new element to the existing div which has id="addNewOneHere"</li>
    </ol>
</p>
<div id="addNewOneHere">This is the div where you'll add your new element using Javascript.  </div>

CSS

div#addNewOneHere div#myNewDiv {
    background-color:red;
}

JavaScript

// your solution here:
// ------------------_

// DO THESE THINGS [1,2,3,4,5]: 
// 1) Create a 'DIV' element node and assign it to a variable:
	let newDiv = document.createElement("div");

// 2) Csing setAttribute(), give it an ID attribute of "myNewDiv":
	newDiv.setAttribute("id", "myNewDiv");

// 3) Create a text node with some text of your choosing, and assign it to a variable:
let textNode = document.createTextNode(`This is my new "text node," which I have placed in my "newDiv," which has an ID of "myNewDiv." That newDiv (#myNewDiv) has then been inserted into the existing HTML Element (div) with an ID of "addNewOneHere." I could have written this particular text without backticks, but I wanted to use quotation marks to enhance clarity of information transference to the viewer of this page; so I chose to do that, ` + "instead of this method. It is my fervent wish that this humble submission is acceptable to the powers that be. This page throws no errors.");

// 4) Append you text node to your element:
newDiv.appendChild(textNode);

// 5) Append your new element to the existing div which has id="addNewOneHere":
addNewOneHere.appendChild(newDiv);