0

If I'm not mistaken, embedded scripts pause the parsing of html in order to run, yet I see scripts that reference the id of an html element that appears after the script itself. How is the script able to "find" that element by id, if the parser has presumably not yet reached that element yet?

For example, many sites using Datatables runs this in the head of the html file, far before the table corresponding to that id appears.

$(document).ready( function () {
    $('#table_id').DataTable();
} );

2 Answers2

2

The function passed to $(document).ready only runs once the DOM is loaded; once the full HTML has been downloaded and parsed by the browser. The $('#table_id') - the part that actually searches through the DOM for the element - doesn't run until later.

You can declare a function that references something that doesn't exist yet. The only limitation is that the something should exist by the time you run the function.

If your code had been

const table = $('#table_id');
$(document).ready( function () {
    table.DataTable();
});

it would not have worked, because in that situation, $('#table_id') is run immediately, before the element is findable in the DOM.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • I see, thank you so much! I've only recently began working with JQuery and in hindsight this should have been obvious just from the naming of "ready". However, to confirm, if I were just to, say, try to get the table by id using the regular "get by id" function before that element appears, then that would cause issues, right? – Each One Chew Feb 24 '21 at 20:33
1

JQuery will wait for document to be fully loaded, and then get the element.

Saggy
  • 75
  • 7