Reputation: 94319
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.
Upvotes: 1
Views: 74
Reputation: 15772
It's like that because after
inserts your content but returns the original element, the paragraph. So your code is saying "insert this button after the p" then "insert this span after the p" (which also happens to be before the button).
To get what you want, pass both items to after
:
$(this).after(btn,span);
Upvotes: 3
Reputation: 150040
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()
inserts btn
such that it immediately follows your <p>
and then the second call inserts span
so 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:
<p>your para content</p>
<button>button</button>
<span>span</span>
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, so
$(this).append(btn).append(span);
// will give you
<p>your original para content
<button>button</button>
<span>span</span>
</p>
// (indenting added just for clarity)
Note 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:
var ele = $('<button>button</button>'),
span = $('<span>span</span>');
$("p").after(span).after(ele);
http://jsfiddle.net/nnnnnn/whY4B/7/
Upvotes: 4