Is there an undefined error when clicking on a row in a dynamically created table?

When creating a table and adding a row click event with the purpose of retrieving the value of the first td, the following code is used:

function bclick(){
    var result=[];
    SAPget.step4QueryTable(function(data){
    var tbody=document.querySelector("tbody");
         for(var i=0;i<data.length;i++)  
            {
                var tr=document.createElement("tr");
                tbody.appendChild(tr);
                var td=document.createElement("td");  
                tr.appendChild(td);
                td.innerHTML=data[i].code; 
                var td1=document.createElement("td");
                tr.appendChild(td1);                
                if (data[i].name!="")
                    { 
                        td1.innerHTML=data[i].name; 
                    }
                else
                    { 
                        td1.innerHTML="";    
                    }
                tr.onclick=function fun(){

                    alert(this.children("td:first"));
                    }  

            }

        }
    )
}

Despite efforts, the code always returns "undefined" when tested. Further debugging in IE reveals that the children have a length of 2 but the value is empty. Could someone please help identify the issue? Thank you.

Answer №1

To retrieve the first child of the tr element, you can follow these steps:

Firstly, utilize the following code:

alert(this.firstElementChild.textContent);

It's important to note that the children method returns an HTMLCollection. Therefore, instead of using children, opt for firstElementChild.textContent.

In addition, if you wish to access the text from another child element, you can refer to:

this.children[1].textContent // The first td will be at index 0 and the second td at index 1

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

Ensure that the form is validated when the radio buttons belonging to an unfamiliar group are

Looking to implement form validation that only triggers when all group radio buttons are checked. The challenge is making this dynamic as the number of radio button groups may vary. Is there a way to determine the number of groups in a form? This functio ...

Possible revision: "Exploring ways to iterate through an array of objects in Node/Express and verify if a corresponding entry exists in a MongoDB

Working on building a web application using the MEAN stack and Yelp API to retrieve an array of objects representing local businesses. I manipulate this data on the front-end, but before sending a response, I need to verify if a specific object exists in m ...

What is the best way to utilize a single component for validating two other components?

I am encountering an issue with my components setup. I have three components in total: GalleryAddComponent, which is used to add a new element, GalleryItemComponent, used to edit an element, and FieldsComponent, the form component utilized by both GalleryA ...

Ways to style a div element in CSS to achieve a unique shape

Hello there! I'm looking to achieve a tilted background div effect. Anyone have any tips or ideas on how I can do this? I'm new to web development and would appreciate the guidance. https://i.stack.imgur.com/wyj1X.png ...

What could be the reason for my inability to retrieve req.user.username with passport.js?

I recently started using passport.js for authentication and I'm encountering an issue. When I log in via Google, the only information available to me through req.user is the user id. I have provided my passport setup code, along with the routes, hopin ...

Tips for adjusting the search bar's position on a mobile device when it is activated by the user

I need help with an open source project where I am developing a search engine using Angular. When using smaller screen sizes, the search bar is positioned in the middle but gets hidden behind the keyboard terminal when clicked on. Can anyone advise on ho ...

Iterate over JSON elements beginning with a specific pattern

What is the best way to iterate through JSON objects that specifically start with a certain format? For example, if we have a JSON structure like this: { "END": true, "Lines": "End Reached", "term0": { "PrincipalTranslations": { // nest ...

Alter the color of the initially chosen option in the dropdown selection

I'm struggling to modify the color of the initial selection while keeping the remaining selection-options at their default black color. Unfortunately, I haven't been successful in achieving this. Currently, all colors are #ccc. What I want is fo ...

City-based Address Suggestions with Google API Places

I have been struggling to find a solution to this specific issue without any luck. Your assistance would be greatly appreciated. Currently, I am attempting to implement autocomplete address functionality using Google API with the following code: var inpu ...

Utilize Ajax to open and close an HTML tag within separate div elements

I am facing a challenge in my project where I have to dynamically open and close a form using ajax. The form needs to be opened within a div, and then closed in another div below it like the following: Opening form (header div) $('#header').h ...

Tips for retrieving nested objects in a get request

A dilemma I'm facing involves a form that effectively sends and saves JSON data to MongoDB using mongoose. However, the issue arises when attempting to access this data as the nested objects display on the get route html page as: { synth: { patch_na ...

Detecting changes in input elements when setting values in AngularJS

Access Code: http://jsfiddle.net/mb98y/309/ HTML <div ng-app="myDirective" ng-controller="x"> <input id="angular" type="text" ng-model="data.test" my-directive> </div> <button onclick="document.querySelector('#angular&a ...

The Magnificent jQuery Widget Factory's _trigger Instance

When utilizing the _trigger function to initiate events, I often come across a recurring issue that I struggle to fully comprehend. The problem arises when there are multiple instances of my widget on the same page. In such cases, the most recently instan ...

Transform JSON data into an HTML table display using JavaScript/JQuery

To retrieve the JSON output on the user interface, I use the following function: $("#idvar").click(function(){ var d1 = document.getElementById("dText"); var d2 = document.getElementById("dJson"); var mytext = d1.textContent; alert(mytext); $.po ...

Implement a callback function to dynamically generate variables and display them within an HTML element

Apologies in advance for any errors I may make as I am a beginner when it comes to javascript, jquery, and json. I have a script that retrieves data from a json file and displays it on a webpage using javascript, jquery, ajax (I believe), and json. When ...

Generating hills with PlaneGeometry in Three.js

Currently, I am searching for a straightforward technique to generate non-uniform hills in Three.js. By utilizing particles and positioning them with a sine wave algorithm like the following snippet: x = Math.random() * 1000 y = Math.sin( x / freq ) * ...

Steps to Change the Default Value of Ant Design Date Picker upon Date or State Modification

AntD Version : 5.0 Upon loading the page, the default date is displayed, but I am passing a date stored in a state object. However, after successfully loading the page, changing the state of the date from one component does not update the default value of ...

merging pictures using angular 4

Is there a way in Angular to merge two images together, like combining images 1 and 2 to create image 3 as shown in this demonstration? View the demo image ...

Is Javascript necessary for submitting a form to a PHP script?

In my current project, I am working on a page to edit information in a database. While I know how to create the form in HTML and the PHP script that runs on the server, I am facing a challenge with JavaScript. My understanding of JavaScript is limited, and ...

Creating a dynamic list in HTML by populating it with randomly selected words using JavaScript

Check out my awesome code snippet function wordSelect() { var words = ["Vancouver", "Whistler", "Surrey", "Victoria", "Kelowna"]; //List of randomly-selected words from above var selectedWords = []; for(let i = 0; i &l ...