-3

PLEASE FORGET THIS QUESTION

I forgot that this page is in the transition from prototype.js to jQuery, and $() refers to prototype.js and jQuery() refers to jQuery

There are 42 or so answers which say it works. IT DOES NOT FOR ME!! It is not a duplicate answer, something must be different,

"Everywhere" the solution for "Does element exist?" is listed as

if ($("#notexist").length > 0)

if ($("#notexist").length > 0) {alert("exists");} else {alert("Doesn't exist");}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

`

However, if I'm using the debugger in chrome, it throws error TypeError: Cannot read property 'length' of null if the element doesn't exist?

Has chrome suddenly changed how .length works? Or is it just assumed that the error is ignored?

Must I put it in a try/catch?

Leif Neland
  • 1,416
  • 1
  • 17
  • 40
  • 1
    Can you put together a [MCVE] illustrating the error, ideally in a live snippet, so we can see it for ourselves too and try to figure it out? – CertainPerformance Feb 17 '20 at 01:16
  • Does this answer your question? [Is there an "exists" function for jQuery?](https://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery) – Kurt Feb 17 '20 at 01:29
  • 2
    The code snippet works as expected for me... – David Feb 17 '20 at 01:30
  • The snippet works for me too, however the same doesn't in my code. – Leif Neland Feb 17 '20 at 01:50
  • 1
    @LeifNeland: That pretty strongly suggests that the problem isn't what you think/assume it is. The same code, under the same conditions, running in the same browser produces the same results. Something else is different about your code, something not shown in the question. – David Feb 17 '20 at 02:00
  • Have you installed jQuery yet? – Refael Feb 17 '20 at 02:41

1 Answers1

1

You do need to install jQuery on your site. You do not have jQuery installed.

Explanation: When you open a debugger in Chrome, it will assign the $ as an alias to document.querySelector if it is not already assigned. This function returns null when the element doesn't exist. Hence you get TypeError: Cannot read property 'length' of null.

patstuart
  • 1,931
  • 1
  • 19
  • 29
  • See edit, $ referred to prototype.js, not jQuery The page is slowly being rewritten from prototype.js to jQuery, a function at a time- – Leif Neland Feb 17 '20 at 02:48