Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

150
Views
Functions accessible from different scripts but constants aren't when added via JQuery html()

I'm working on a legacy system where an endpoint sends an HTML content that when received in the frontend is added to a div: $('#some-div').html(htmlContent).

That works fine, but I am observing something strange, when I define some constants in a <script> they appear as undefined in the scripts that continue:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
  // This simulates the content retrieved from the server
  let contentFromBackend = JSON.parse("{\"text\":\"<script>\\n    const someConst = \'hello\'\\n\\n    function someConstFn() {\\n        return \'hello\'\\n    }\\n<\/script>\\n\\n<script>\\n    console.log(someConstFn()) \/\/ This works!\\n    console.log(someConst) \/\/ This fails saying that someConst is undefined!\\n<\/script>\"}")['text']

  // Appends to div
  $('#some-div').html(contentFromBackend)
})
</script>

<div id="some-div"><div>

If the content is generated statically (for example, with a Template Renderer like Twig or plain HTML) both the constant and the functions work perfectly. var also works fine. Why does this happen?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!