I've been trying to run the following code:


  var myContract;

  function startApp() {
    myContract = new web3.eth.Contract(crowdsaleABI, 

  function displayPrice() {
    myContract.methods.tokenPrice().call((err, result) => {
    console.log(web3.utils.fromWei(result, "ether"))});

  window.addEventListener('load', function() {

    // Checking if Web3 has been injected by the browser 
    if (typeof web3 !== 'undefined') {
      // Use Mist/MetaMask's provider
      web3 = new Web3(web3.currentProvider);
      document.write("You are connected to MetaMask");
    } else {
      // Handle the case where the user doesn't have web3.
      document.write("You are not connected to MetaMask");
      web3 = new Web3(new 
    // Now you can start your app & access web3js freely:


 console.log("Hello World");


However, I've been getting the following errors:

Uncaught TypeError: Cannot read property 'methods' of undefined
Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child

Particularly, first error is stopping me from doing any progress. I'm running web3 1.0.0-beta.34 (checked using npm ls web3).

1 Answer 1


Your displayDevice() call is executed before the window loads (where you call startApp()).

So myContract is not initialized yet in your displayPrice function.

Your error is telling you "myContract is undefined".

  • What changes would I have to implement? Sorry, still very new to coding in general.
    – dkelsen
    Commented Jul 29, 2018 at 16:32
  • Look up what the $(document).ready and window.addEventListener('load', ...) do (and how they differ).
    – Xilis
    Commented Jul 29, 2018 at 17:49
  • Try dropping the window.addEventListener part (keep the code inside it's callback). The problem is that displayPrice() is called before startApp(). displayPrice() uses myContract, which is initialized in startApp(). I suggest you place a couple of console logs inside the $(document).ready, the eventListener callback and so on to get a sense in what order things are being executed (keep in mind the event callback is asynchronous).
    – Xilis
    Commented Jul 29, 2018 at 17:57

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.