'const elements defined in js module - cant access as DOM content not loaded yet
Using the below example. The const element test_el is null because the DOM content isn't loaded yet. So test() raises an error.
Wrapping the const definition in a onload event doesn't seem to work as its now now in the same scope as the function.
Whats the correct method of achieveing this - I know I can add the const within the function but it needs to be reused over multiple functions (not in this example)
main.js
import {test} from "../import.js"
window.addEventListner("load", ()=>{
test()
})
import.js
const test_el = document.getElementById("test_div")
export function test(){
console.log(test_el.innerText)
}
Solution 1:[1]
// you can call
// all the tests that are dependent of `test_el` from one parent function
// after getting value of `test_el`
export function runTests() {
const test_el = document.getElementById("test_div");
if(test_el) {
firstTest(test_el)
secondTest(test_el)
} else {
throw new Error('Element not found.')
}
}
function firstTest(element){
assert(element.innerText.equal('someText'))
}
function secondTest(element){
assert(element.classList.includes('someClass'))
}
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 |
