Search code examples
jqueryappendto

jQuery - appendTo previous / preceding element


I couldn't find this on here already, and am hoping somebody can help.

I need the link (.more) to be appended to the paragraph that precedes it - I'm sure this is simple enough, but can't quite get it right:

<p>Lorem ipsum</p>

<p>Lorem ipsum</p>

<p>Lorem ipsum</p>

<a href="#" class="more">Read more</a>

<p>Lorem ipsum</p>

There may be more paragraphs in the final HTML, the reason I need to do this is CMS-related. But based on the above, my aim would be:

<p>Lorem ipsum</p>

<p>Lorem ipsum</p>

<p>Lorem ipsum <a href="#" class="more">Read more</a></p>

<p>Lorem ipsum</p>

I've tried:

$(".more").appendTo("p");

But obviously this will append it to all paragraphs... perhaps this is a job for prevAll, but I can't quite put my finger on it.

Many thanks in advance for your help!


Solution

  • HTML

    <p>Lorem ipsum</p>
    <p>Lorem ipsum</p>
    <p>Lorem ipsum</p>
    <a href="#" class="more">Read more1</a>
    <p>Lorem ipsum</p>
    <a href="#" class="more">Read more2</a>
    

    JS

    $('p').each(function(e){
        if($(this).next('a').hasClass('more'))
           $(this).html($(this).html()+" ").append($(this).next('a')); 
    });​
    

    Example1 and Example2 with multiple a tags.