Why does variable passing use 'object Text' instead of passing values?

In my for loop, I am dynamically creating a table with radio buttons and trying to create labels dynamically as well. However, when I pass the variable to the label text node, it prints out 'object Text' on the page instead of the expected value.

function filter() {
  // Fetches tool types for filter table
  // The removeDuplicates function returns a Set so I convert toolTypes to an Array here. 
  var toolTypes = removeDuplicates(tools);
  
  //types contains the values:
  // var types = ['Nut', 'Slot', 'Phillips', 'Torx'];

  var types = Array.from(toolTypes);
  // Add the word 'All' to the array
  types.splice(0, 0, 'All');

  var table = document.getElementById('tableFilter');
  var tr = document.createElement('tr');
  table.appendChild(tr);

  var td = [];
  var text = [];
  for(let i = 0; i < types.length; i++) {
    td[i] = document.createElement('td');
    text[i] = document.createTextNode(types[i]);
    // td[i].appendChild(text[i]);
    tr.appendChild(td[i]);

    
    // Create radio button
    var radioButton = document.createElement("input");
    // Set type of new radio button
    radioButton.setAttribute("type", "radio");
    // Set id of newly created radio button
    radioButton.setAttribute('id', 'radioType' + i);
    // Set unique group name of radio buttons
    radioButton.setAttribute('name', 'radioType');
    
    // Create label for Radio button row
    var lblRadioType = document.createElement('label');

     

// HERE IS INSERTION
    console.log(text[i]);
   // create text node for label text
    var textNodeRadioType = document.createTextNode(text[i]);

    // add text to newly created label
    lblRadioType.appendChild(textNodeRadioType);
    // Assign ID to label text
    lblRadioType.setAttribute('id', 'textRadioType' + i);
    
    // add radio button
    td[i].appendChild(radioButton);
    // add label text for radio button
    td[i].appendChild(lblRadioType);
    
    // add space between two radio buttons
    var space = document.createElement('span');
    space.setAttribute('innerHTML', '&nbsp;&nbsp');
    lblRadioType.appendChild(space);
  }
}

I attempted moving the variable declaration inside the for loop but still faced the same issue. It seems that the variable is somehow out of scope.

Instead of inserting my tool type values (All, Nut, Slot, Phillips, Torx), it inserts 'object Text.'

Answer №1

One problem is that text[i] is a Text object, not a string value. When you pass text[i] to document.createTextNode(), it creates a new text node with the default string representation of the Text object, which is "object Text".

To solve this issue, you must access the nodeValue property of the Text object, which holds the actual text content. You can achieve this by making the following adjustment:

var textNodeRadioType = document.createTextNode(text[i]);

Change it to:

var textNodeRadioType = document.createTextNode(text[i].nodeValue);

By implementing this change, you should be able to resolve the problem and properly display the accurate text values within the label.

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

Ways to limit the number of duplicate elements in an array to X

I am facing a challenge where I need to limit the number of duplicates within an array to a maximum of 8. While I have learned how to filter out duplicates from an array by referring to Stack Overflow questions, I am unsure on how to specifically retain up ...

Guide to utilizing JSDoc within your local project

Objective My goal is to utilize jsdocs with npm in my project. Experience I am new to working with npm and its plugins. Recently, I came across jsdoc and attempted to incorporate it into my project without success. Attempted Solution Initially, I inst ...

`Failure to prompt an error following an unsuccessful post request in a node.js application using axios and express`

I'm currently facing an issue while trying to implement password change validation. The problem lies in not receiving the errorMessage from the server in case of an error. Although I've successfully managed to update the password and send back a ...

The addition of a slash between the hashtag and the anchor name by Fullpage.js is causing conflicts with ng-include

My experience with using fullpage.js on a simple site alongside angular directives has been met with an issue. When including a .phtml file, the anchor functionality of fullpage.js stops working as it adds a slash before and after the anchor name. UPDATE ...

Are two JavaScript functions conflicting with each other?

Seeking assistance with integrating a Javascript/PHP/AJAX clock into my website to display various timezones (tutorial link: ) The clock implementation is functional, but it conflicts with an existing javascript stopwatch on the page, causing the clock no ...

An alternative solution for supporting Edge Chromium is utilizing synchronous AJAX requests within the beforeunload event

While attempting a synchronous ajax request during the beforeunload event, I encountered an error stating that synchronous ajax requests are not supported in chromium browsers during page unload events. I am seeking alternatives for making a synchronous a ...

Is it possible to find out which JavaScript file the AJAX function is using to send a request to a Java servlet?

I am facing an issue with two js files, one.js and two.js. Both of these files make ajax requests to the same Java servlet class(AppController.java). Here is the code from one.js: function addOne(){ var formData = $('#form1').serialize(); ...

Despite being invoked five times and enclosed in a React.Fragment tag, the functional component is still not displaying any content

<html lang="en"> <head> <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js& ...

Calculating the total of every potential arrangement of arrays with a flexible amount of arrays, enforcing restrictions, and providing back indexes

This question has been inspired by this original question. The modification involves returning not only the elements themselves but also their indices. While I've successfully made adjustments to arraysums() and arraysums_recursive(), I'm facing ...

Styling a nested scrollbar using JQuery

I am looking to customize two scrollbars using a jquery plugin or JS library. Here is the HTML code: <div id="container"> <div class="fixedHeightContainer"> <div class="fixedHeightContent"> Lorem ipsum dolor sit amet, con ...

Comparing Dates in Node.js using JavaScript and Sorting Arrays based on Date Values

Is JavaScript lacking a basic Date comparison feature similar to Python? Within my Node.js script, these lines are present: console.log(Date(2012,11,10) < Date(2012, 11, 9)) console.log(Date(2012,11,10) > Date(2012, 11, 9)) Surprisingly, both of t ...

Having difficulties with the 'client request' function in the latest version of Next.js (13.5.1) - still receiving server-side responses

In the current version of Next.js (13.5.3), I am utilizing 'use client' but the component is still rendering from the server-side. Additionally, I am finding it challenging to integrate Tailwind and Ant Design (antd) together in Next.js. If anyo ...

The decision will be dependent on the outcomes provided by the $resource promise

I have been working on calling my API with AngularJS to retrieve a list of 'reports' and then displaying them in a modal or saving the sale depending on whether any results were returned. I've been struggling with this for a while and would ...

Utilizing a function argument within the :not() selector

I am currently working towards the objective of selecting all elements in my document except for those within a specific class. This is what I have come up with so far: var x = document.querySelectorAll(":not(.myParameter)"); My aim is to make 'myPa ...

Using Regex to detect recurrent (similar) patterns in jQuery <input> tags

I need assistance with ensuring that users input article numbers in the correct format, like this: ABC_ABC123; AB__B2A4; ABF_323WET; ... Currently, I have a regex pattern that works for one article number: var mask1 = /^([A-Z]{2})([A-Z|_]{1})_([A-Z0-9]{ ...

Executing React's useEffect hook twice

As I work on developing an API using express.js, I have implemented an authentication system utilizing JWT tokens for generating refresh and access tokens. During testing with Jest, Supertest, and Postman, everything appears to be functioning correctly. O ...

Formulate a jQuery array consisting of droppable components

I have successfully implemented draggable li-elements and droppable boxes using jQuery UI. Here is my structure: A list of 3 different permission types <ul> <li data-action="create">Create</li> <li data-action="edit">Edi ...

Saving Python array output as a CSV file

I need assistance with scraping data from a website using Python and BeautifulSoup. While I am able to extract the data and store it in a variable, I am encountering difficulties saving it to a CSV file. Here is the code snippet that I have been working on ...

The code functions perfectly on my local machine, however it is not cooperating on the HostGator server

A selection box based on values should appear in text fields, The current code is functional in local host but not working on the hostgator server For example, displaying country options based on the selected state and districts based on the selected sta ...

How can I retrieve Feature Information exclusively from the currently visible WMS layers in OpenLayers 3?

I am working with an Openlayers map that features multiple WMS layers. I am trying to use the "getGetFeatureInfoUrl" function to request feature information, but only for the layers that are currently visible on the map. Additionally, if there are multiple ...