You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript HTML DOM浏览器运行异常:跟随YouTube教程编写代码未获预期输出

Fixing Your "Age in Days" JavaScript Issue

Hey there! Let's get your code working properly. I noticed two key issues that are stopping your age calculator from outputting the expected result:

1. Typo in the DOM selection method

You used document.getElementsById("flex-box-result") — but the correct method for selecting a single element by ID is document.getElementById() (no extra 's' at the end). The getElementsById function doesn't exist in JavaScript; plural getElementsBy* methods are for selecting multiple elements (like getElementsByClassName), but we only need one element here.

2. Missing string-to-number conversion

The value returned by prompt() is always a string. When you subtract it from 2021, JavaScript might sometimes coerce it to a number, but it's not reliable. Explicitly converting the input to a number will prevent weird bugs (like if someone enters non-numeric text).

Corrected script.js code

//challenge 1: your age in days
function ageInDays() {
  var birthyear = prompt("What year were you born?");
  // Convert the input string to a number with parseInt
  var age = (2021 - parseInt(birthyear)) * 360;
  let h1 = document.createElement('h1');
  let textAnswer = document.createTextNode("You are "+ age + " days old");
  h1.setAttribute('id', 'ageInDays');
  h1.appendChild(textAnswer);
  // Fixed the getElementById typo
  document.getElementById("flex-box-result").appendChild(h1);
}
function reset() {
  document.getElementById("ageInDays").remove();
}

A quick side note: Using 360 days per year is a simplified estimate, but that's totally fine if that's what your tutorial is teaching!

内容的提问来源于stack exchange,提问作者tinu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 20:07:38