Trying to understand how document fragment works and why it is being attached to only one element

Trying to understand how document fragment works and why it is being attached to only one element

I am trying to understand how document fragment works. Here is html and jQuery code.

  1. <h2>one</h2>
    <h2>two</h2>
    <h2>three</h2>
  1. value = jQuery('<p>hello world</p>');

  2. $('h2').each(function(){  
  3.   $(this).before(value);
  4. });
  5.  

After the jQuery code the html looks like this.

  1. <h2>one</h2>
    <h2>two</h2>
    <p>Hello World</p>
    <h2>three</h2> 

With the help of debugger I was able to detect that p element was added before first h2. Then it was detached from there and added before second h2. And then p was detached and added before third h2.

If I change the code to have fragment inside the loop then I get one p before each h2.

  1. $('h2').each(function(){  
  2.   value = jQuery('<p>hello world</p>') ;
  3.   $(this).before(value);
  4. });
  5.  

So my question is how does document fragment works? Why is it getting attached and then detached in the first case?