21

Getting this error on Safari 10

Happens when a const is given a name that's exactly the same as an id of any element on the page.

const abc = document.querySelector("#abc"); //err
const abz = document.querySelector("#abc"); //no err
var abc = document.querySelector("#abc"); //no err

Is there a reason for this?
I know you can access the elements via window.abc, is that part of the why?

Test:

<!doctype html>
<html><body>
<div id="alpha"></div>
<script>
    const alpha = document.querySelector('#alpha');
    console.log(alpha);
</script>
</body></html>
9
  • Can't replicate (STP 10.1)
    – joews
    Oct 17, 2016 at 21:23
  • Errr well that's jsfiddle. Try it raw? I'll post a test.
    – House3272
    Oct 17, 2016 at 23:20
  • Just tried on it STP, same error.
    – House3272
    Oct 17, 2016 at 23:22
  • I can replicate with HTML, thanks. The error doesn't occur if you run const alpha... in a setTimeout callback. It looks like a temporal binding bug in Safari. I guess that's why a fiddle doesn't hit it.
    – joews
    Oct 18, 2016 at 9:28
  • 1
    @joews But const in setTimeout would be scoped to the callback function called after timeout, not the global scope, so it doesn't really relate to this problem.
    – pawel
    Oct 18, 2016 at 18:17

3 Answers 3

43

This is apparently a problem Safari has with declaring a let/const variable that shares the same name as a selected id attribute. I had some variables declared with const as you did and got the same error. Changed to let and still got it. Changed to var and it worked.

5
  • 3
    Thanks, your answer solved my today's problem with Safari. I want that state that I hate Safari more than IE !
    – realtebo
    Jun 19, 2017 at 13:17
  • 1
    Wow... this is awful... one year later and still not fixed... is safari becoming the new IE ???
    – Kokodoko
    Sep 13, 2017 at 19:12
  • 1
    I have no words. Just... wow. A quick search and replace of const to var fixed it.
    – Domino
    Sep 22, 2017 at 20:28
  • 1
    Solvem my problem with WKWebViews in iOS too.
    – Ali Safari
    Aug 31, 2022 at 7:53
  • 1
    Thank you. Here we are in 2023 and this problem still exists in Safari. I changed const to var and it fixed the issue. Aug 11 at 18:30
7

This must be linked to this webkit bug

In the meantime you may either replace const by var, or change the name of your variable (eg: _alpha).

0

Nathan's answer is correct. Instead of using var I just changed my const to have a different case than the id. So...

const Abc = document.querySelector("#abc"); 

Still hacky, just another option.

Your Answer

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

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