Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript code not working as intended

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. :)

like image 388
Abdullah Hamzic Avatar asked Aug 28 '26 03:08

Abdullah Hamzic


2 Answers

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:

  • MDN Docs: childNodes
  • MDN Docs: children
like image 95
Andrew Burgess Avatar answered Aug 29 '26 18:08

Andrew Burgess


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:

  • ParentNode.firstElementChild
  • Node.textContent
  • Function.prototype.call()
  • Document.querySelectorAll()
  • Array.prototype.forEach()
like image 26
w35l3y Avatar answered Aug 29 '26 16:08

w35l3y



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!