Linked Questions

Popular Questions

JavaScript GetElementById is Null but Element Has a Value

Asked by At

I'm trying to pass a value from JavaScript to HTML for a Chrome extension. I keep getting an error that the element being referenced is null.

popup.html

<!doctype html>
<html>
<head>
    <link rel="stylesheet" href="style.css">
    <script type="text/javascript" src="popup.js"></script>
</head>
<body>
    <div>
        <h3>Output</h3>
        <br>
        <output id="outputKey">Output goes here</output>
    </div>
</body>
</html>

popup.js

chrome.storage.sync.get("key", function (value) {
    console.log("Output key value: " + value["key"]);
    console.log("Popup output key value: " + document.getElementById("outputKey"));
    //Set document.getElementById("outputKey") to value["key"]
  });

The result is that they key value retrieved from storage is valid and is logged to the console correctly when using console.log("Output key value: " + value["key"]);. I would like to set this value to the output element's value to display it on popup.html. I am getting an error that says document.getElementById("outputKey") is null.

I was wondering if this is because the extension's page is only displayed when the extension button is clicked in the browser. I tried adding the following with no luck.

popup.js

...
window.onload = function () {
    chrome.storage.sync.get("key", function (value) {
    console.log("New key value: " + value["key"]);
    document.getElementById("outputKey") = value["key"];
});

Related Questions