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:
childNodeschildrenThat 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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With