user4175297 user4175297 - 1 month ago 9
Ajax Question

Append elements to div but before another element inside the div

I'm appending content from an ajax call into an element, but I have a button in that element that I'd like to always stay at the bottom underneath all the appended elements. But right now the appended elements are going after the button.

HTML

<div id="pagecontent" class="wrapper">
<!-- WANT APPENDED ELEMENTS TO APPEND HERE -->
<div class="btnholder">
<a id="continue" class="continue" href="javascript:;">get more</a>
</div><!-- WANT TO KEEP AT BOTTOM HERE-->
</div>


JQUERY

success: function(data){
$("#pagecontent").append(data);
},


The (data) coming in is basically a simple div that continually appends new divs.

<div class="floatleft"></div>


Important to note that I don't think prepend() works properly because I have a button that fetches records from a database and is supposed to append each record under the other. With prepend I think it brings the records on top of the other as opposed to below.

Answer

Use before()

var  i = 1
function prependData(){
     
    $( ".btnholder" ).before("<div class='floatleft'>someText"+i+"</div>");
  i++;
 };
<script   src="https://code.jquery.com/jquery-2.1.4.min.js"   integrity="sha256-8WqyJLuWKRBVhxXIL1jBDD7SDxU936oZkCnxQbWwJVw="   crossorigin="anonymous"></script>
<div id="pagecontent" class="wrapper">
  <!-- WANT APPENDED ELEMENTS TO APPEND HERE -->
     <div class="btnholder">
      <a id="continue" class="continue" href="javascript:;">get more</a>
     </div><!-- WANT TO KEEP AT BOTTOM HERE-->
 </div>
<button onClick="prependData()">Click Me</button>