Blur event flow and synchronization of DOM updates

The following code has this behavior when I focus on the input and then click the delete button:

  1. Mousedown callback function is triggered, however input does not blur immediately cause of ev.preventDefault()

  2. Container gets removed by (at least it should be) the mousedown function.

  3. Blur callback function is then triggered since the removal of the container caused the input to lose focus

  4. It prints the container element in the console, even though I was expecting null. Wasn’t it removed by the mousedown callback function?

  5. It then (in my understanding) removes the container element that for some reason was not removed by the mousedown func.

  6. the mousedown func then doesn’t find an element to remove so it throws a DOMException.

I am not sure if the process happens exactly like I described it. If I comment out the container.remove line in the blur func, first the element will be printed in the console by the blur func and after “null” will be printed by the mousedown func.

I cannot understand how the blur func is seemingly called before the mousedown one. For the blur func to be called the container has to be removed. So how does the blur func find it in the DOM again and how does it remove it if it’s already been removed?

const inp = document.querySelector("input");
const container = document.querySelector("#container");
const btn = document.querySelector("button");

btn.addEventListener("mousedown", (ev) => {
  ev.preventDefault();
  console.log('Before remove',document.querySelector("#container"));  
  container.remove();
  console.log('After remove',document.querySelector("#container"));
});

inp.addEventListener("blur", () => {
  console.log('In blur',document.querySelector("#container"));
  container.remove();
});
<div id="container">
  <input />
  <button>Delete</button>
</div>