<h3>Practice Set #2, Week 8, Modifying the DOM</h3>
<p>We're going to practice the steps of manually creating and 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>
/*
* 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.// your solution here
*/
// 1. create a 'DIV' element node and assign it to a variable myNewDiv
var myNewDiv = document.createElement('div');
console.log("This is an element of type: ", myNewDiv.nodeType);
// 2. using setAttribute(), give it an ID attribute of "myNewDiv"
//var id = document.createElement("id");
myNewDiv.setAttribute('id', 'myNewDiv');
//myNewDiv.hasAttribute('id');
//console.log("This is an element of type: ", myNewDiv.nodeType );
//myNewDiv.id = 'myNewDiv';
// 3. create a text node with some text of your choosing, and assign it to a variable
var t = document.createTextNode('Hello World');
console.log("Text in var t is: ", t);
// 4. append you text node to your element
myNewDiv.appendChild(t);
console.log("Inner HTML of myNewDiv is: ", myNewDiv);
// 5. append your new element to the existing div which has id="addNewOneHere"
addNewOneHere.appendChild(myNewDiv);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.