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.
-
<h2>one</h2>
<h2>two</h2>
<h2>three</h2>
- value = jQuery('<p>hello world</p>');
- $('h2').each(function(){
- $(this).before(value);
- });
After the jQuery code the html looks like this.
-
<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.
- $('h2').each(function(){
- value = jQuery('<p>hello world</p>') ;
- $(this).before(value);
- });
So my question is how does document fragment works? Why is it getting attached and then detached in the first case?