Search code examples
jqueryprepend

prependTo item only once on div


Let's say I have this data and I just want to prependTo only once, because when I tried to prependTo the $('.entry-title') to ('.container) it display twice every article.

<article class="blogpage-posts">
  <div class="container">
    <a href="#">Data One</a>
    <h1 class="entry-title">Data to Prepend One</h1>
  </div>
</article>

<article class="blogpage-posts">
  <div class="container">
    <a href="#">Data Two</a>
    <h1 class="entry-title">Data to Prepend Two</h1>
  </div>
</article>

This is the code...

$(document).ready(function(){
     $('.entry-title').prependTo('.container');
});

This is the result when using that code.

Data to Prepend One
Data to Prepend Two <--- the data the display twice
Data One

Data to Prepend Two
Data to Prepend One <--- the data the display twice
Data One Two

Solution

  • Use this code:

    $(document).ready(function(){
         $('.entry-title').each(function(){
            $(this).prependTo($(this).closest('.container'));
         });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <article class="blogpage-posts">
      <div class="container">
        <a href="#">Data One</a>
        <h1 class="entry-title">Data to Prepend One</h1>
      </div>
    </article>
    
    <article class="blogpage-posts">
      <div class="container">
        <a href="#">Data Two</a>
        <h1 class="entry-title">Data to Prepend Two</h1>
      </div>
    </article>