Error is thrown when attempting to access nested elements using GetElementsByClassName within the window.onload function

I have a funky looking table on my webpage, here's an example:

<body>
<table class="table table-bordered">
    <thead>
    <tr>
        <th>#</th>
        <th>Product name</th>
        <th>Product description</th>
        <th>Price</th>
        <th>Details</th>
    </tr>
    </thead>
    <tbody>


    <tr style="height: 50px;">
        <td>1</td>
        <td>Mug</td>
        <td>Perfect for drinking stuff</td>
        <td>41</td>
        <td><a href="/products/detail?id=1"><i class="glyphicon glyphicon-info-sign"></i></a></td>
    </tr>

    etc....

</body>

I'm currently in the middle of writing some crafty JavaScript code to grab hold of that 'a' tag and its link. Unfortunately, I can't just slap an id onto it for easy access so I've resorted to this method:

var btn = document.getElementsByTagName("tbody")[0].getElementsByTagName("a")[0];
console.log(btn.href);

But wouldn't you know it, I keep running into the same issue: btn is undefined.

Even though when I try to display the tbody element, it shows up as an object. So why isn't this working when trying to dig deeper into its child tags?

Just to throw it out there - this JavaScript snippet is being run within the window.onload function.

Answer №1

It is recommended to utilize document.querySelectorAll() for this specific scenario:

var btn = document.querySelectorAll("tbody a")[0];
console.log(btn.href);

Example:

var btn = document.querySelectorAll("tbody a")[0];
console.log(btn.href);
<table class="table table-bordered">
<thead>
    <tr>
        <th>#</th>
        <th>Product name</th>
        <th>Product description</th>
        <th>Price</th>
        <th>Details</th>
    </tr>
</thead>
<tbody>
    <tr style="height: 50px;">
        <td>1</td>
        <td>Mug</td>
        <td>Perfect for drinking stuff</td>
        <td>41</td>
        <td><a href="/products/detail?id=1"><i class="glyphicon glyphicon-info-sign"></i></a></td>
    </tr>
</tbody>
</table>

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

Encountering a fresh issue after updating to TS version 4.4.3 while accessing properties of the top "Object may be 'null'."

After upgrading my project to TypeScript 4.4.3 from 3.9.9, I encountered a change in the type declarations for the top property. My project utilizes "strictNullChecks": true, in its configuration file tsconfig.json, and is browser-based rather t ...

Tips for verifying blank form fields

Is there a way to validate empty form fields before submission and show an alert? This validation is important as some fields are hidden using v-show. Here is an example: <!DOCTYPE html> <header> <script src="https://unpkg.com/vue@n ...

Struggling to retrieve a JSON object from an Express and Node application, only receiving an empty result

Can anyone assist me? I'm having trouble with the res.json() function in my code. It seems to work after the first request, but not after the second. Right now, my application is quite simple - it scrapes user data from social media platforms like Twi ...

What is the best way to show inline icons within menu items?

Issue Upon selecting an option from the menu, I encounter a problem where the icon (represented by a question mark inside a speech bubble) appears on a different line than the text ("Question"). Fig. 1. Display of menu after selection with the icon and t ...

What is the best way to obtain the post id when making a JavaScript Ajax request?

I am currently developing a website similar to Stack Overflow for practice purposes. I am currently working on implementing the voting system. My goal is to have an Ajax call triggered when the upvote or downvote button is clicked, sending parameters such ...

encountering a problem with retrieving the result of a DOM display

private scores = [] private highestScore: number private studentStanding private studentInformation: any[] = [ { "name": "rajiv", "marks": { "Maths": 18, "English": 21, "Science": 45 }, "rollNumber": "KV2017-5A2" }, { "n ...

The character 'T' cannot be assigned to the data type 'number'

When working with an optional type argument function RECT(T), I encountered a situation where I need to check if the argument is an instance of date. If it is, I convert it to a number; if not, I use the number directly. However, I keep getting an error ...

What purpose does Webpack serve in injecting React?

Within my webpack entry file, I have the following code snippet: import ReactDOM from 'react-dom'; import Layout from './components/Layout'; // ... dialog = document.createElement("dialog"); ReactDOM.render(<Layout dialog={dialog} ...

What is the best way to dynamically hide a textbox in JSP based on the selection of a

On my JSP page, I have a textbox and a checkbox. I attempted to use jQuery and JavaScript to hide the textbox when the checkbox is checked, but it doesn't seem to be working. Below is the code snippet: <p class="contact"> <input id="check" n ...

The process of reversing an array is not fully completing due to the pop method being used within a loop

Note: I've been immersed in code for hours now and have reached a stage where I'm starting to doubt the spelling of every word or question if I have dyslexia. Despite this, I know this should be a simple question. I want to create a basic functi ...

Trying to call an applet method using JavaScript will not be successful

When trying to invoke methods of a Java applet using JavaScript, I encounter an issue that requires the site to be added to trusted sites and security set to low in order for it to work properly. Otherwise, an error is thrown: Microsoft JScript runtime ...

Create a function in JavaScript that can generate a random number a specified number of times based on user input

I have been struggling to develop a JavaScript program that can generate a random number multiple times based on user input. Despite numerous attempts, I haven't been able to get it to work. Below is the code snippet I've been working with: f ...

Converting an array of date strings to a single string in JavaScript

Here is the JSON format I received with dynamic data: {"range":["2018-07-23T16:03:26.861Z","2018-07-23T16:03:26.861Z"]} Now, I need to convert this into the following format: range(20180723,20180723) Below is my code snippet : var data:Date[] = {"rang ...

Increasing the grid size in React Bootstrap 5 for added flexibility

Customizing React Bootstrap Sizes WPW Container Max-Width sx < 576px - none sm > 567px - 540px md > 768px - 720px lg > 992px - 960px xl > 1200px - 1140px xxl > 1400px - 1320px Desiring a New Size Category: I am interested in ad ...

Display the React component following a redirect in a Next.js application that utilizes server-side rendering

Just starting out with next.js and encountering a problem that I can't seem to solve. I have some static links that are redirecting to search.tsx under the pages folder. Current behavior: When clicking on any of the links, it waits for the API respo ...

Access external link without leaving current page

Dear webmasters, I am seeking advice, tools, or guidance to solve a simple problem. I have my own HTTP server that responds to HTTP requests. Example: If I visit the link: http://ip_server/link1, it performs a specific functionality If I visit the lin ...

Monitoring the progress of file uploads within itemView

In the process of developing an application using Marionette/Backbone, I have successfully implemented file uploads over an AJAX call. Now, I am looking for a way to provide users with feedback on when they can select the uploaded file and proceed with mod ...

Implementing Promises in AngularJS Controller: A Comprehensive Guide

I'm currently working on implementing a basic function using promises in one of my controllers to make sure it works correctly before adding more complex functionality. I keep running into a "TypeError: undefined is not a function" error when trying t ...

Is there a way to integrate Javascript code with a React component?

I need to find a way to include this block of code in just one specific React component. Any suggestions? <!-- Create a button that your customers click to complete their purchase. Customize the styling to suit your branding. --> <button sty ...

Guide to using Ajax to load a partial in Ruby on Rails

Whenever a search is triggered, I have a partial that needs to be loaded. This partial can take a significant amount of time to load, so I would prefer it to be loaded via Ajax after the page has fully loaded to avoid potential timeouts. Currently, my app ...