I am teaching myself javascript and don’t understand the results I am getting from some example code. I have pruned the code for brevity.
The html:
<body>
<h1>firstChild and lastChild Property Lab</h1>
<hr />
<form>
<label>Enter some text to add or replace in the OL element:</label>
<br />
<input type="text" name="input" size="50" />
<br />
<input type="button" value="Insert at Top"
onclick="prepend(this.form)" />
<input type="button" value="Append to Bottom"
onclick="append(this.form)" />
<br />
<input type="button" value="Replace First Item"
onclick="replaceFirst(this.form)" />
<input type="button" value="Replace Last Item"
onclick="replaceLast(this.form)" />
</form>
<ol id="myList">
<li>Initial Item 1</li>
<li>Initial Item 2</li>
<li>Initial Item 3</li>
<li>Initial Item 4</li>
</ol>
</body>
The javascript:
// helper function for prepend() and append()
function makeNewLI(txt)
{
var newItem = document.createElement("LI");
newItem.innerHTML = txt;
return newItem;
}
function replaceFirst(form)
{
var newItem = makeNewLI(form.input.value)
var firstLI = document.getElementById('myList').firstChild.value;
document.getElementById('myList').replaceChild(newItem, firstLI);
}
I thought if I entered some text in the text box and clicked the Replace First Item button that the first item in the list would be replaced. However, the first time I do that it is prepended to the top of the list and the list now has 5 items. Then if I change the text in the text box and click the Replace First Item button again the first item in the list is changed.
I don’t understand why this is happening. I expected the replacement would happen whenever I clicked the button. I am working with Firefox 4 on Ubuntu 10.04. Also, if I try to replace the last item in the list result is the same as I outlined above.
Thanks, Jim
There are 2 things wrong there. Firstly, you are selecting the
valueinstead of the element withvar firstLI = document.getElementById('myList').firstChild.value;so usevar firstLI = document.getElementById('myList').firstChild;instead.Secondly, believe it or not your
firstChildis aTextNodewith empty text with your current markup. Remove the empty space between<ol>and the first<li>so that its<ol><li>...., like here:http://jsfiddle.net/niklasvh/5anyq/