http://jsfiddle.net/DerekL/whY4B/
$("p").each(function(i) {
var btn = $('<button>button</button>'),
span = $('<span>span</span>');
$(this).after(btn).after(span);
});
So here I have <p>s in my HTML and I use .after() to create buttons and spans:
$(this).after(btn).after(span);
btn comes first, and span comes last. But the result is the opposite: btn comes last, and span comes first.
What the heck? How come it’s like that and it is very confusing. Please help.
The
.after()method inserts the element passed as a parameter immediately after the element you call it on. So in your code the first.after()insertsbtnsuch that it immediately follows your<p>and then the second call insertsspanso that it immediately follows your<p>.Obviously the fix for this is to add them in the opposite order.
Note that the result will be:
I.e., the new elements really are added after and not as children of your paragraph. If you use
.append()it will add them as children, soNote also that if you are adding exactly the same content to each paragraph you don’t need the
.each()because this will do it too:http://jsfiddle.net/nnnnnn/whY4B/7/