How does HTML code get executed?

On this session, I noticed that we’re passing an id
to the Label tag even before we create the actual input element of that id.

  <label for="anchovy">Anchovy</label>
  <input id="anchovy" name="topping" type="checkbox" value="anchovy">

And I’m surprised that it works because on the line where label gets executed(idk if this is the right term for html), the id “anchovy” doesn’t exist yet. It’s like printing a variable before creating the variable in actual programming languages.
I’m just curious, how do browsers run this code?

1 Like

HTML is a declarative language. It does not execute. The browser uses a parsing engine to construct the DOM tree from the markup. Each node is an object with attributes, but can also be a tree if there are child elements.

As for the id, it is static and only comes into play if the user clicks the label. That event will tell the browser to set focus on the associated element. That is all it does.