I experimented in [jsfiddle] with a function created to add the newly created TextNodeto <p>in the HTML below:
<button onclick="addTextNode('YES! ');">YES!</button>
<button onclick="addTextNode('NO! ');">NO!</button>
<button onclick="addTextNode('WE CAN! ');">WE CAN!</button>
<hr />
<p id="p1">First line of paragraph.</p>
Here is my javascript:
function addTextNode(text) {
var newtext = document.createTextNode(text),
p1 = document.getElementById("p1");
p1.appendChild(newtext);
}
It works great. However, crux detects itself when I try to make a "joblubive" of my javascript by removing the behavior from the markup ...
<button>YES!</button>
<button>NO!</button>
<button>WE CAN!</button>
<hr />
<p id="p1">First line of paragraph.</p>
then using a loop to attach addEventListenerto each element <button>, which in turn uses a child TextNodeto call addTextNode:
function addTextNode(text) {
var newtext = document.createTextNode(text),
p1 = document.getElementById("p1");
p1.appendChild(newtext);
}
var btns = document.getElementsByTagName("button");
for(i = 0; i < btns.length; i++){
var button = btns[i];
button.addEventListener("click", addTextNode(button.innerHTML));
}
Two strange things happen to my code:
When the [jsfiddle's] Code Wrap parameter is set to "no wrap-in head", nothing happens.
, Code Wrap 'onLoad', 'onDomReady' 'no wrap-in body', , this.
- , ?