4

In this example, why does the variable foo not raise a ReferenceError? There is no variable declaration, but it's clearly in scope after the DOM is rendered. What's the relationship between the DOM node id and the javascript namespace? I'm running this with jest.

import React from 'react';
import { render } from '@testing-library/react'

test('renders a div', () => {
  const { utils } = render(<div id="foo"/>)
  expect(foo).toBe(true)
})

Jest reports:

Expected: true
Received: <div id="foo" />

I really wish the test would crash instead, because in my real example I accidentally passed an undefined variable to expect(), which just happened to share the name of a rendered DOM node's id.

7
  • 3
    Browsers do that for stupid legacy reasons. Commented Apr 14, 2020 at 21:06
  • 1
    @Pointy can you provide a source that documents this behavior? Commented Apr 14, 2020 at 21:08
  • document.write('<div id="foo"/>'); console.log(window.foo) Commented Apr 14, 2020 at 21:09
  • 1
    @RobertStiffler well probably, but I've been living with it for the better part of 20 years. IE used to do that forever, and Firefox didn't, so there were endless bugs because of that. It's similar to the issue of the global event reference vs. the parameter passed to event handlers. Commented Apr 14, 2020 at 21:29
  • 1
    @Pointy Based on the accepted answer, it appears this was originally unstandardized behavior of IE, but has now been "standardized by HTML5, whose approach is to document and standardize every terrible practice inflicted on us by browser authors, making them part of the web forever". :( Commented Apr 14, 2020 at 21:36

1 Answer 1

3

Elements with ids become global variables

Not the same question, but the answer to your question is another SO question:

Do DOM tree elements with ids become global variables?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.