"use strict";
var myButton = document.getElementById("myButton");
myButton.onclick = function (){
var newNode = document.createTextNode("Blueberry");
var item = document.getElementId("myList").childNodes[0];
console.log(item);
item.replaceChild(newNode,item.childNodes[0]);
}
#myButton {
color: blue;
border: 1px solid black;
width: 200px;
text-align: center;
}
<h1>Learning the Basics of How DOM Functions</h1>
<h3>
What is DOM?
</h3>
<p id="intro">
DOM stands for "Document Object Model" and it is a plaform (as well as a language-netural interface) that allows programs and scripts to dynamically access and update the content, structure, and style of a document.
<br>
<br>
Visit <a href="https://www.w3schools.com/js/js_htmldom.asp">this page </a> if you want a further explanation.
</p>
<h3>
Test Your Knowledge:
</h3>
<p>
The purpose of this homework exercise is to introduce you to some examples of DOM manipulation within the HTML. Let's get started!
</p>
<h4>
Part 1
</h4>
<p>
Write some lines of code so that when you click on the button below, one of the values in the list gets replaced without another value.
<br>
<button type="button" id="myButton">Click This to Replace</button>
<ul id="myList">
<li>
Apple
</li>
<li>
Watermelon
</li>
<li>
Pumpkin
</li>
<li>
Strawberry
</li>
<li>
Kiwi
</li>
</ul>
<b>Replace the item that doesn't belong with something that does.</b>
</p>
I created a createTextNode() function to create a text node onClick of a <button> element, however, it's not working as expected.
My Goal: onClick - I want to replace an item from the list I've created using the createTextNode function whenever the <button> is clicked.
Here's the JS Fiddle.
Thanks so much in advance!
Start by calling methods which exist:
onclickinstead ofonlickdocument.getElementByIdinstead ofdocument.getElementIdUse
childrenrather thanchildNodessince childNodes includes things like code comments.You can simplify the code to just use textContent rather than createTextNode -
Look at your developer console for errors to see what you've done wrong and add console.log's to check if your callback is being called on click.
While you're at it change your myButton to an actual
<button>