0

I tried this:

in constant.js

const CONFIRM_BUTTON = document.querySelector(".confirm-button");
export { CONFIRM_BUTTON };

in some-file.js,

import { CONFIRM_BUTTON } from './constants';
CONFIRM_BUTTON.onclick = someFunction;

I am getting Cannot set property 'onclick' of null error in doing so.

If in some-file.js file, I do following, it works:

const CONFIRM_BUTTON = document.querySelector(".confirm-button");
CONFIRM_BUTTON.onclick = someFunction;

I am trying to do this const CONFIRM_BUTTON = document.querySelector(".confirm-button"); once and use it multiple js files? How can I do that?

2
  • Are you sure the selector is being evaluated after the DOM is ready? If the DOM is not ready when the document.querySelector(...) is evaluated, it will return null. Commented Mar 2, 2019 at 20:55
  • .confirm-button in not in the DOM on initial load, but instead of importing CONFIRM_BUTTON element, if I declare it in the same file and use it, it works. This works ` const CONFIRM_BUTTON = document.querySelector(".confirm-button"); Commented Mar 2, 2019 at 21:05

1 Answer 1

1

you need just export CONFIRM_BUTTON without curved brackets

Sign up to request clarification or add additional context in comments.

2 Comments

I get Declaration or statement expected error in doing so; const CONFIRM_BUTTON = document.querySelector(".confirm-button"); export CONFIRM_BUTTON;
have you tried to use const CONFIRM_BUTTON = document.getElementsByClassName("confirm-button") ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.