Instead of using a string in the createTextNode() function, consider utilizing a variable

I am attempting to use JavaScript to add another list item to an unordered list. I want the list item to display dynamic content based on a pre-existing variable. While I can successfully append a list item by using a string, things go awry when I try to incorporate a variable.

//Adding to List
listOfPlayers.style.display = "block";
var node = document.createElement("LI");
var textnode = document.createTextNode(playerInput.value);
node.appendChild(textnode);
listOfPlayersNumerated.appendChild(node);

The issue arises with this section of code:

var textnode = document.createTextNode(playerInput.value);

When I used a hardcoded string instead (as shown below), it worked without any problems:

var textnode = document.createTextNode("New Player");

Answer №1

After making some adjustments, you can now easily identify the source of the variable...

At the top:

var inputPlayer = document.getElementById("inputPlayer");

To retrieve the value of the input, simply add .value as shown below:

//Adding to List
listOfPlayers.style.display = "block";
var playerName = playerInput.value;
console.log(playerName);
var node = document.createElement("LI");
var textnode = document.createTextNode(playerName);
node.appendChild(textnode);
listOfPlayersNumerated.appendChild(node);

The value will be logged in the console, but it may not appear on the unordered list (ul).

Answer №2

It seems that the scope was causing some trouble. Despite being able to print out the variable in the console, it was not cooperating with .createTextNode(). I decided to move

var playerName = playerInput.value;

Up and outside of the current function. It's strange that console.log() accepted it but not .createTextNode() in that particular scope.

By declaring the new variable outside of the function, it looks like I've managed to resolve the problem.

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

Verify the presence of blank space with javaScript

I currently have a text box on my website. <input type="text" name="FirstName" value="Mickey"> My goal is to prevent the user from entering empty spaces, tabs, or new lines in the text box. However, I want to allow spaces between characters. Does a ...

Using the v-for directive in Vue.js to loop through an array and display

Looking at the image provided, I am trying to access the content. I attempted to do so using element.comments.content, but it did not seem to work as expected. Here is the snippet of code: <div class="fil-actualites-container"> <div cl ...

Utilizing hover effects and timeouts to conditionally show React components

I encountered a challenging React layout dilemma. It's not a complex issue, but rather difficult to articulate, so I made an effort to be as clear as possible. The data I have maps individual components in the following way: map => <TableRow na ...

What is the reason behind the shifting behavior of e.currentTarget when using event delegation in jQuery?

Click here for the code snippet <div id="container"> <button id="foo">Foo button</button> <button id="bar">Bar button</button> </div> $('#container').on('click', function(e) { var targ ...

Preventing Bull Queue from automatically re-starting jobs upon server restart

Currently, I am utilizing the bull queue system for processing jobs. Imagine a scenario where a job is in progress with an active status and I restart my development server. Upon restarting the worker script, the job remains in the active state within the ...

Eliminable Chips feature in the Material UI Multiple Select component

The Material UI documentation showcases a multiple select example where the selected options are displayed using the Chip component and the renderValue prop on the Select. By default, clicking on the current value opens the list of available options. I am ...

Transform tree-like JSON array with nested arrays into flat JSON array

I have an array tree in JSON format with potentially unlimited nesting: const namesArrayTree = [ { "name": "Peter" }, { "name": "folder1", "isArray": true, " ...

Arrange the list by first names in the array using Ionic 3

What is the process for arranging a list by firstName from an array? This is my code in my.ts file: initializeItems(){ this.items = [ { avatar: '../../assets/imgs/profile1.jpg', firstName:'Sterlian', lastName:'Victorian ...

Steps for displaying a bootstrap modal in alignment with the triggering button's position

Recently diving into the world of bootstrap and AngularJs has been quite the learning experience for me. One challenge I encountered was trying to implement a bootstrap modal dialog box to show additional details within a table column. My goal was to hav ...

Tips for attaching a load event to an image

Although I am aware that $('img').load(function(){}) can function properly, I am interested in having the img dom that has not been initially created also be able to trigger the event. I am curious as to why the following code snippet does not wo ...

Failure to display React component on screen

I have developed a React microfrontend application consisting of two sub-apps rendered through the container/ project. Both sub-apps render perfectly in isolation on localhost:8083. However, when attempting to view them via localhost:8080/dashboard, I am p ...

Discover the Magic of CSS Animation

I am not experienced in CSS animations and have limited knowledge about animations. I am trying to create an animation where a grey box slides down from the top line above the login/register section, but currently it only fades in. If anyone can provide an ...

Unable to move cursor in contenteditable section

I am currently working on developing a rich text editor in React, but I have encountered an issue that has me stuck. The problem I am facing is that as I type each character, the insertion point does not update accordingly, causing the cursor to remain stu ...

Having trouble getting the on:dblclick event to trigger on a row within a list using S

I am currently using Sveltestrap and I am in need of a double click handler for a row: <ListGroupItem on:dblclick={handler(params)}> <Row> <Col><Icon name=........</Col> ... </Row> </ListGroupItem> Int ...

Polymer: Basic data binding is not functional in the second element

After dedicating 6 hours to this problem, I still can't seem to find a solution. Below is the code snippet from index.html: <flat-data-array availableModes="{{modes}}" id="dataArray"></flat-data-array> <flat-strip-view availableModes=" ...

Redux-form fails to retrieve the value of the SelectField

I'm trying to work with a simple form using react and redux-form. My goal is to gather all the field values from my form and send them to my RESTful API using jQuery ajax. Unfortunately, I've run into an issue where redux-form doesn't seem ...

Convert string IDs from a JSON object to numerical IDs in JavaScript

My goal is to convert the IDs in a JSON object received from PHP into numeric keys using JavaScript. The initial structure of my JSON object looks like this: let foo = {"66":"test","65":"footest"}; What I aim for is to transform it into this format: let f ...

When the user scrolls to the right side of the page, fresh content will be loaded

While there are many plugins available that enable content to be loaded when the user reaches the bottom of the page, I have been unable to find a jQuery plugin that allows content to be loaded when the user reaches the right side of the document. Does an ...

What is the reason behind the failure to update the state via a reducer and Object.assign?

I'm attempting to develop a reducer without utilizing ES6. It's an outmoded PHP application that lacks a build process for transpilation. I am initializing the state: let defaultState = { accountTypes: { individual: { c ...

What is the best way to navigate through images only when hovering?

I have a website that showcases a collection of images in a creative mosaic layout. Upon page load, I assign an array of image links to each image div using data attributes. This means that every image in the mosaic has an associated array of image links. ...