I’m a jQuery newbie. Here are two code snippets that move the h1 element below the first paragraph. They do precisely the same thing.
$('p').eq(0).after(function() {
return $(this).prev();
});
and
$('p').eq(0).after( $('h1') );
Which code practice is preferable? Why?
Thanks in advance for any help.
EDIT:
Here’s the html.
<article>
<h1>Post</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua.
</p>
<p>
<span class=co>Lorem ipsum dolor sit amet</span>, consectetur adipisicing elit, sed do eiusmod
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua.
</p>
</article>
The first code: select all
pelements, get the first found and put after it a element returned on the callback.thison callback is referent to the selectedp. So theconsole.logreturn thepelement. Thereturnreturn the element before the selectedp. On this case, the selectedpis the firstLorem ipsum. And the previous element is theh1. Then theh1is returned and attachedafter()thepelement.The second code: will work similar, for this specific case. But watch out! On this case you will get all
pelements and filter it, getting the first one (like first code) so you will attachafterit all foundh1elements. How in your example HTML code you have only oneh1element, it not will be a problem. But if you have two or more, you will have trouble!