JavaScript script unexpectedly malfunctioning

http://codepen.io/abdulahhamzic/pen/xVMXQa

This project is a challenge for me. Trying to place the letters of userWord in five different boxes, I encountered an issue where only every second letter appears when using this JavaScript code. It's puzzling why it happens this way.

for (var i = 0; i < 5; i++) {  
        document.getElementsByClassName("letters")[input].childNodes[i].innerHTML = "<h1>" + userWord[i].toUpperCase() + "</h1>";
    }    

I'm still searching for a solution. :)

Answer №1

The property called childNodes retrieves all nodes within an element, including text nodes and the space between elements. If you only want child elements, use the children method instead.

Here's a snippet to illustrate:

for (var i = 0; i < 5; i++) {  
    document.getElementsByClassName("letters")[input].children[i].innerHTML = "<h1>" + userWord[i].toUpperCase() + "</h1>";
}

(I tried this in your CodePen, and it worked as expected.)

For further information, refer to:

Answer №2

Here is the code snippet to achieve that:

for (let i = 0; i < 5; i++) {
    document.getElementsByClassName("alpha")[i].firstElementChild.textContent = userInput[i].toUpperCase();
}

Alternatively, you can use:

Array.prototype.slice.call(document.querySelectorAll(".alphabets > .alpha"), 0, 5).forEach(function (node, index) {
    node.textContent = userInput[index].toUpperCase();
});

For further reference, please check out the following documentation:

Answer №3

When using ChildNodes, you are grabbing text instead of what you actually want, which 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++;
}

Check out this WORKING DEMO!! http://codepen.io/nicholasabrams/pen/yOZwNP

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the functionality of Angular.js through QUnit testing

Is it possible to integrate angular.mock.inject() with QUnit instead of Jasmine? In the provided code snippet, angular.mock.dump is defined, but unfortunately angular.mock.inject remains undefined. <!DOCTYPE html> <html ng-app="mymodule"> & ...

What is the best way to design a bookmarklet that can overlay an HTML/div layer and apply CSS styles from an

Is there a way to incorporate a bookmarklet that can bring in a new layer/div with additional HTML and CSS from an external file, overlaying it on the current page? If anyone has an example of a bookmarklet that achieves this, would you be willing to shar ...

How to display specific JSON objects that meet particular criteria in HTML cards using Ionic and Angular?

As a beginner in Ionic/Angular, I am attempting to fetch data from a JSON file and display it using cards in the HTML. The JSON contains numerous objects that are either marked as "deTurno == true" or "deTurno == false". Here is what I have so far: publi ...

Steps for Setting a Radio Button Group back to a Specific Value

I am currently working with a set of radio buttons that are displayed using ng-repeat. The last radio button is selected by default (ng-checked="$last"): Status: <span ng-repeat="button in statusList"> <input type="radio" name="status" ng-mod ...

Warning: Potential unhandled promise rejection in React class component

I'm trying to implement a promise inside a class so that depending on whether it resolves or rejects, another method of my component is executed. Below is the code I have: var promise = new Promise((resolve, reject) => { let name = 'DaveA&ap ...

Grammarly is seamlessly inserting padding into my body element

After setting up my website on GitHub, I ran into an issue where the Grammarly Chrome extension was automatically adding a padding-top attribute to the body tag. <body data-new-gr-c-s-check-loaded="14.1028.0" data-gr-ext-installed="" ...

Clicking the button will close the active tab in Firefox

I need help with a webpage that has a popup. When the user clicks the OK button in the popup, I want the current tab to close. The OK button is an HTML input tag. I've tried various ways of using JavaScript's close method and searched online, but ...

Exploring the method of implementing a "template" with Vue 3 HeadlessUI TransitionRoot

I'm currently working on setting up a slot machine-style animation using Vue 3, TailwindCSS, and HeadlessUI. At the moment, I have a simple green square that slides in from the top and out from the bottom based on cycles within a for-loop triggered by ...

Encountered a JQuery error in the application: trying to call the 'open' method on dialog before initialization is complete

I am having trouble integrating a dialog box into my application and encountering the error mentioned above. Here is the jQuery code I'm using: $( "#dialog" ).dialog({ autoOpen: false, width: 450, modal: true, ...

What is the best way to make my page headers resize with a responsive layout?

Currently, I am working on a website that needs to be fully functional on both mobile devices and computers. I have successfully implemented Bootstrap-responsive to make many elements work, but now I am focusing on the hero-unit for the homepage. Specifica ...

Which shortcuts or techniques in jQuery/JavaScript can I implement to simplify this code further?

I've written a script to handle responsive design for smaller devices and display a toggle menu instead of a full-width menu. The current script works, but I find it messy. How can I make this code more minimalistic and efficient? Is it good practice ...

Javascript does not function on sections generated by ajax

I'm facing an issue with a JavaScript function not working on a dynamically generated part using AJAX. Here is the AJAX call: <script> $(window).on('scroll', function() { $("#preloadmore").show(); if ($(window).height() + $(window ...

Updating JSON data in Node.js by adding a new object

I'm facing a situation where I have a JSON file acting as a database to manage users by adding, removing, and modifying them. Currently, I have the following code snippet: 'use strict'; const fs = require('fs'); let student = { ...

What is the process for setting up a redirect to the login page in ASP.NET?

When using ASP.NET, what is the most effective method for redirecting a user to the login page if they try to access a page intended for registered users? Please note that although I am utilizing ASP.NET WebForms, there are no actual WebForms involved. Th ...

Exploring the Various Textures within the CANVAS 2D Context

Exploring new techniques for filling the canvas, I am currently trying to add texture to an object similar to the blobs from the blob example (http://www.blobsallad.se/). The challenge is that the current example is utilizing the 2D context without webGL i ...

Managing the dropdown selection will reset the text field when the onchange event is triggered with the submission of the form

My form has multiple sections, and whenever I choose an answer from the dropdown in one section, it clears the data entered in another section. I am using the "onchange" event to display a calculation at the bottom of the form before submission. Section B ...

Sending a form without the need to reload the page

While it's known that Ajax is the preferred method to submit a form without refreshing the page, going through each field and constructing the Post string can be time-consuming. Is there an alternative approach that utilizes the browser's built-i ...

Proper method of defining an action in Vuex

Do you think it's sufficient to create vuex-actions as simple as a1, without chaining then/catch calls? Or should I always go with creating Promises as in a2 (and also adding a reject branch)? Appreciate your insights... import Vue from 'vue& ...

Placing the right column above the left column for better visibility

I am facing a challenge with the layout of my two columns. When viewing on desktop: On mobile: The current design has the column on the left, "Browse Programs", appearing below the left column. I am looking for a solution to have it appear above the left ...

What is the best way to overlay an SVG line on top of a CSS style?

Is there a way to make SVG lines appear on top of CSS-styled elements in my HTML file? I have a white background SVG created with JavaScript using d3, and I am adding CSS-styled rectangles on top of it. However, I also want SVG lines (created with JavaScri ...