http://codepen.io/abdulahhamzic/pen/xVMXQa
This is my project. I want to put the letters of userWord in the five boxes. Why does it happen with only every second letter when I use this JavaScript code?
for (var i = 0; i < 5; i++) {
document.getElementsByClassName("letters")[input].childNodes[i].innerHTML = "<h1>" + userWord[i].toUpperCase() + "</h1>";
}
I can't seem to figure out the solution. :)
The childNodes
property returns all the nodes within an element, and these include text nodes, the whitespace between the actual elements. Instead, try using children
, which only returns child elements, which is what you want.
For example:
for (var i = 0; i < 5; i++) {
document.getElementsByClassName("letters")[input].children[i].innerHTML = "<h1>" + userWord[i].toUpperCase() + "</h1>";
}
(I tested this in your CodePen, and it did exactly what you want.)
For more details see:
childNodes
children
That would be:
for (var i = 0; i < 5; i++) {
document.getElementsByClassName("letter")[i].firstElementChild.textContent = userWord[i].toUpperCase();
}
or
Array.prototype.slice.call(document.querySelectorAll(".letters > .letter"), 0, 5).forEach(function (node, index) {
node.textContent = userWord[index].toUpperCase();
});
Documentation:
ChildNodes is grabbing text, what you want is .children()
var word = 'МАЈКА';
var userWord;
var theNode;
var theClone;
var input = 0;
function game() {
userWord = document.getElementById("text").value;
theNode = document.getElementsByClassName("letters")[input];
theClone = theNode.cloneNode(true);
document.body.appendChild(theClone);
for (var i = 0; i < 5; i++) {
document.getElementsByClassName("letters")[input].children[i].innerHTML = "<h1>" + userWord[i].toUpperCase() + "</h1>";
}
input++;
}
WORKING DEMO!! http://codepen.io/nicholasabrams/pen/yOZwNP
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.