'Html ReferenceError: document is not defined
My error = ReferenceError: document is not defined
document.getElementsByClassName("text_status").innerHTML = 'hello'
I am trying to change the text of an element in my html. This is the beginning of my html file I am running this code in my electron JS app
<script defer src="js/appfunction.js"></script>
<script defer src="js/myscript.js"></script>
What I am doing wrong or what should I change ?
Solution 1:[1]
The document
object is only available after
the DOM tree
has been built and not beforehand.
Using defer
in
your <script>
tag(s)
is
correct though best practice now dictates one places any <script>
tags between the closing </body>
and </html>
tags.
When updating the page element with a class name of text-status
, if you are only updating the text within the element
then you can use innerText
instead
of innerHTML
.
Lastly, document.getElementsByClassName()
returns an array of objects. A particular object can be access by referring to its index number.
EG: document.getElementsByClassName()[0]
. To access all objects, one
can loop through them.
TIP: The trick to remembering if a particular Javascript method returns an array of objects is by its name. If the method name contains a plural word (IE: Elements vs Element) then it will usually return an array and not a single object.
If the element value you need to change is a unique element then you should refer to that element by id
and
use document.getElementById('text-status')
.
See document.getElementById() for more
information.
Not knowing how your html document is constructed and assuming the value is to be changed by your render process, I have created the below code for your understanding.
index.html
(render process)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div class="text_status">Div 1</div>
<div class="text_status">Div 2</div>
<div class="text_status">Div 3</div>
<div id="text_status">Div 4</div>
</body>
<script src="appFunction.js">
<!-- <script src="myscript.js"> -->
</html>
appfunction.js
(render process)
// Use element(s) class name
let elements = document.getElementsByClassName('text_status');
console.log(elements); // Testing
elements[1].innerText = 'Div 2 - Updated'; // Change second element
// Use element id
let element = document.getElementById('text_status');
console.log(element); // Testing
element.innerText = 'Div 4 - Updated';
If the changing value of your element is to come from your main process then you should re-word your question as the answer will be more involved.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | midnight-coding |