Both the scripts files index.js and exam.js are linked respectively to index.html and exam.html. but styling in index.js is causing this error
(index.js:193 Uncaught TypeError: Cannot read properties of null (reading 'style') at index.js:193:37 (anonymous) @ index.js:193)*
in the exam.js file
index.js file setup
document.querySelector('.container').style.backgroundColor = 'green'
export const colors = {red: 'red', blue: 'blue'}
exam.js file setup
import {colors} from './index.js'
console.log(colors);
note both script tags have the type attribute (modules) in their respective html file. How do I stop the document.querySelector('.container').style.backgroundColor = 'green' from giving me the above error, because without the above styling the code exports perfectly?
Are you sure that '.container' exists in the DOM when the script is executed? Just try something like this:
export const colors = ...your object...;
const targetEl = document.querySelector('.container');
if(!targetEl) {
return;
}
targetEl.style.backgroundColor = 'green';