为何出现Uncaught TypeError错误?如何实现信息正常渲染无报错?
Hey there, let's break down this problem and fix it step by step!
First, let's understand the core error
The error Uncaught TypeError: Cannot read property 'insertAdjacentHTML' of null at renderHTML tells us exactly what's wrong: you're trying to call the insertAdjacentHTML method on a null value. That null value is your bitprice variable—meaning document.getElementById('bitprice') couldn't find any element with that ID in the DOM when it ran.
Why does this happen? Because you declared var bitprice = document.getElementById('bitprice'); outside the $(document).ready() callback. At that point, the browser hasn't finished loading the full DOM yet, so the element doesn't exist to be fetched.
Fix 1: Move element selection inside the ready callback
The simplest fix is to move the line that grabs the bitprice element into the $(document).ready() function. This ensures the DOM is fully loaded before you try to access elements:
$( document ).ready(function() { // Now the DOM is ready—we can safely grab the element var bitprice = document.getElementById('bitprice'); var bitcoin = new XMLHttpRequest(); bitcoin.open('GET', "https://api.coindesk.com/v1/bpi/currentprice.json"); bitcoin.onload = function() { var bitdata = JSON.parse(bitcoin.responseText); // Now bitprice is not null, so this will work bitprice.insertAdjacentHTML('beforeend', `<p>Bitcoin Price (USD): ${bitdata.bpi.USD.rate}</p>`); }; // Don't forget to send the request! bitcoin.send(); });
Fix 2: Use jQuery selectors (cleaner, since you're already using jQuery)
Since you're leveraging jQuery, you can simplify element selection with its built-in selectors, which play nicely with the ready callback:
$( document ).ready(function() { var $bitprice = $('#bitprice'); var bitcoin = new XMLHttpRequest(); bitcoin.open('GET', "https://api.coindesk.com/v1/bpi/currentprice.json"); bitcoin.onload = function() { var bitdata = JSON.parse(bitcoin.responseText); // jQuery's append() does the same job as insertAdjacentHTML here $bitprice.append(`<p>Bitcoin Price (USD): ${bitdata.bpi.USD.rate}</p>`); }; bitcoin.send(); });
Quick additional checks to avoid future issues
- Double-check your HTML: Make sure there's actually an element with
id="bitprice"(IDs are case-sensitive, soBitPricewon't work!). For example:<div id="bitprice"></div> - Address other console errors first: Often, one critical error can block subsequent code execution and cause more unrelated errors. Fix this DOM element issue first, then go through the other errors one by one (common culprits include missing script imports or typos).
内容的提问来源于stack exchange,提问作者Ryan Myers

