Challenges with Input Nesting

Why is the word "undefined" appearing on top of my text?


function printName() {
    document.write('My name is John Doe.');
}

function printAge() {
   printName();
   document.write('I am 47 years old.');
}
document.querySelector('.test').innerHTML = printAge();

JSBin link to access the full code.

Answer №1

function displayMyAge(){
        myname();
        document.write('I am 47 years old')

    }
    document.querySelector('.test').innerHTML=displayMyAge()

When displayMyAge() is called, it does not return anything. Therefore, the innerHTML for the selected target remains empty.

This lack of a return value is what causes it to show as Undefined.

Answer №2

When a web browser is processing an HTML document and encounters a script tag, it must execute that script before continuing to build the Document Object Model (DOM). If you try to access document.querySelector('.test') at that moment when it's not yet available, it will return undefined. Below is an example code where the script runs without any issues after the DOM has finished loading.

<!DOCTYPE html>
<html lang="en>
<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="test"></div>
</body>
<script>
    function myname(){
        document.write('I'm John Doe ')
    }
    function myage(){
        myname();
        document.write("I'm 47 years old")
       
    }
  document.addEventListener("DOMContentLoaded", () => {
   document.querySelector('.test').innerHTML=myage()
  });
  
</script>
</html>

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

What is the process of transferring fetched data to a different module?

I am facing a situation with two modules, module.js and controller.js. In the module file, I have the following code: export class Module { constructor(){ const fetchParams = { method: "GET", mode: "cors", c ...

Having trouble getting your AngularJS code to work?

Recently, I decided to experiment with AngularJS and started working on a new project. Below is the HTML code I wrote: <div ng-app ng-controller="nameController"> <input type="text" value="Jack" ng-model="fname" /> <input type="tex ...

Is there a method to prevent data loss on page refresh by persisting data stored in a database?

I'm currently developing a commenting feature for a blog using the latest version of NextJs. The text input collects data and sends it to the 'Vercel' hosted database. I am able to successfully fetch the data from the frontend as expected. ...

Positioning Firefox absolutely within a table-cell element is possible

Interestingly, it's not Internet Explorer causing me trouble this time, but Firefox. Here is the Fiddle link for reference: http://jsfiddle.net/EwUnt/ The purpose of this table is to highlight both the row and column of the cell where the cursor is ...

Create a function in JavaScript that is able to accept a variable number of objects as arguments

I have a good grasp of how to pass infinite parameters in a function in JavaScript. But what about accepting any number of objects as parameters in a function? This is my current implementation: function merge<T>(objA: T, objB: T){ return Object. ...

The JSONP request connected to the user input field and button will only trigger a single time

Hello all, I'm new to this and have been searching the internet high and low to see if anyone has encountered a similar issue before, but haven't had any luck. I've been attempting to set up a JSONP request to Wikipedia that is connected to ...

Unable to generate a fresh directory with mongoose and express

As the title suggests, I am working on an application that generates a link using mongoose _id and express's app.get when certain information is inputted. However, I am facing an issue where I have to reload the entire server in order to access the di ...

Is there a way to change the format of the date "Wed Jan 01 2020 00:00:00 GMT+0530 (India Standard Time)" to JAN 01, 2020 in JavaScript?

I am currently retrieving the date from the database in the format of Wed Jan 01 2020 00:00:00 GMT+0530 (India Standard Time), but I would like it to be displayed in the JAN O1,2020 format without using moment.js. Is there any alternative approach to ach ...

Playing a game of rock, paper, scissors with two players using JavaScript

Hello! I am a beginner in JavaScript and I am trying to create a simple rock, paper, scissors game. However, when I run the code, I receive two prompt messages and an error saying 'TypeError: playerOneChoice is not a function'. What mistake did I ...

Choosing a single item from multiple elements in React using React and typescript

In this particular project, React, TypeScript, and ant design have been utilized. Within a specific section of the project, only one box out of three options should be selected. Despite implementing useState and toggle functionalities, all boxes end up bei ...

Deleting validation messages from my MVC controls

I set up some validation in my Model by adding the following code: [Required] [StringLength(60, MinimumLength = 4)] [Display(Name = "Users code")] public string UserCode { get; set; } When c ...

The best method for quickly loading a webpage that is over 20MB in size

My website is a single-page calendar featuring a full year's worth of images. With 344 requests and a total load size of 20MB, the page consists of a simple PHP script without a database. The requests include a CSS file (15KB), 4 JS files (20KB), two ...

The Bootstrap nav-link class functions perfectly in Firefox, smoothly guiding users to the appropriate section. However, it seems to be experiencing some issues

I am currently working on customizing a one-page web template and I don't have much experience with Bootstrap. The template can be found at . My issue is that the menu items are not functional in Chrome. When I click on any menu item, nothing happens ...

Using React JS to automatically execute an event based on a specific state value

Is there a way to initiate an action from a main component when the child component's state reaches a specific value? Let's consider a scenario where I have a Parent component and a Child component, with the parent's state containing active ...

Tips for eliminating the left and bottom border in a React chart using Chart.js 2

Is there a way to eliminate the left and bottom borders as shown in the image? ...

What is the best way to save a current HTML element for later use?

Here is a simple HTML code that I would like to save the entire div with the class test_area and then replicate it when needed. Currently, my goal is to duplicate this div and place the clone underneath the original element. How can I achieve this? Unfortu ...

Unable to extract the 'id' property from 'params' object in Next.js 13.4 due to its undefined value

I am currently trying to retrieve the [id] URL parameter in Next.js 13.4, but I keep encountering an error stating that params is undefined. Despite extensive online research and seeking assistance from ChatGPT, all I could find were examples for older ve ...

Dropped down list failing to display JSON data

I created a website where users can easily update their wifi passwords. The important information is stored in the file data/data.json, which includes details like room number, AP name, and password. [ {"Room": "room 1", "AP nam ...

Guide to dynamically insert rows in HTML using Vue.js based on the selected option

This is the initial row. Depending on the selection made here, different rows will be displayed <div class="row"> <div class="col-md-4"> <div class="form-group label-floating"> <label class="control-label">Case Type< ...

Implementing custom fonts in Next.js using next-less for self-hosting

Seeking Solutions for Hosting Fonts in Next.js Application I am exploring the idea of self-hosting a font, specifically Noto, within my Next.js application that already utilizes the @zeit/next-less plugin. Should I rely on the npm package next-fonts to h ...