1

I faced this problem when i doing my project and not able to use addEventListener function. So I make new file and try to catch the error, so basically its store null value to the variable that's why i am not able to use. When i use the same code on the console , that was executed and give the expected result but not with VS code.

*JS code

let elem7=document.getElementById("mainDiv")
console.log(elem7)//prints null

elem7.addEventListener('click',function(e){
    console.log("You Clicked")
})  

HTML CODE:

<body>
    <h3>Editable div</h3>
    <div id="mainDiv">

    </div>
</body>
  • Console log actually logs your whole HTML element. – aca Jun 29 '22 at 08:49
  • how you call you js file please ? – AWEMA Agence Web Marketing Jun 29 '22 at 08:49
  • Please double check where you put your js code ! make sure it runs after loading dom. – Xupitan Jun 29 '22 at 08:49
  • @aca your edit introduces different semantics to the code. Therefore, not showing an error. The description in the question shows quite clearly that *something else* is happening. Furthermore, this is a *very* common and *very* well-known problem - if `document.getElementById()` returns `null`, then the element was not found. A lot of times this is because it runs *before* the element exists. The snippet you edited ensures that the code runs *after* the element is created. Thus "fixing" the problem. Please, only add snippets that *don't* hide the real issue. – VLAZ Jun 29 '22 at 08:57
  • @VLAZ You're right. I've removed the Edit part of my answer. – aca Jun 29 '22 at 08:59

0 Answers0