javascript - document.getElementById not working with Webpack -


i've been trying implement basic javascript webpack have found lot of trouble trying basic methods work. know problem js loading before dom fixes issue have been futile.

for instance, i'm trying run let taskinput = document.getelementbyid('new-task'); , when search taskinput variable in console return of uncaught referenceerror: taskinput not defined(…).

i've tried quite few different solutions make code operate after dom has loaded nothing seems work.

i tried basic attempt of putting javascript file @ bottom of dom.

i've tried basic js method so:

  document.onreadystatechange = function() {   if (document.readystate === "complete") {     initapplication();   }  function initapplication() {(... placed code in here ...)} 

i've tried using jqueries

$( document ).ready(function() { }); 

i've tried injecting javascript file html html-webpack-plugin

is there i'm missing webpack?

index.html

<!doctype html> <html>   <head>     <meta charset="utf-8">     <title>sample site</title>     <meta name="viewport" content="width=device-width,initial-scale=1">   </head>   <body>     <button id="new-task">click</button>     <script src="/assets/app.bundle.js"></script>   </body> </html> 

app.js

'use strict';  document.onreadystatechange = function() {   if (document.readystate === "complete") {     initapplication();   } }  function initapplication() {   onbuttonclick(); }  let onbuttonclick = function() {   let taskinput = document.getelementbyid('new-task');   taskinput.onclick = alert('hey'); } 

for instance, i'm trying run let taskinput = document.getelementbyid('new-task'); , when search taskinput variable in console return of uncaught referenceerror: taskinput not defined(…).

first of all, module code in webpack bundles run in own scope, in closure, , not in global scope (which can access window). secondly, if go console , declare variable let, example let = 1, though console operates in global (window) scope, if try window.a undefined because let variables not attached window scope. see this

is there i'm missing webpack?

probably fact code in bundles, generated webpack, not run in global scope, explained above.

if want expose variable global scope in order able use it, debugging purposes, in console, declare window.variablename. or can add breakpoint in code, adding debugger, after variable want check out, without exposing global scope.


Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -