Append/Prepend in DIV with fixed child - jQuery

Asked

Viewed 2,719 times

3

How do I append/prepend a div that has a fixed child using jQuery.

For example:

<div class="container">
    <div class="placeholder"></div>
</div>

When giving the first append/prepend need that the content is inserted after the .placeholder. Next should be relative to the element already added.

For example: Append elem um

<div class="container">
    <div class="placeholder"></div>
    <div class="elem um"></div>
</div>

Append elem dois

<div class="container">
    <div class="placeholder"></div>
    <div class="elem um"></div>
    <div class="elem dois"></div>
</div>

Prepend elem tres

<div class="container">
    <div class="placeholder"></div>
    <div class="elem tres"></div>
    <div class="elem um"></div>
    <div class="elem dois"></div>
</div>

I’ve tried to:

$('.container').find('.placeholder').after().prepend(elem_x);
$('.container').find('.placeholder').after().append(elem_x);

$('.container').find('.placeholder').next().prepend(elem_x);
$('.container').find('.placeholder').next().append(elem_x);
  • already tried the append without the after?

  • Works only for the append, in the prepend the div is inserted before the placeholder.

2 answers

2


You can create a div only to serve as container to the others and add the content within this div. Take an example:

$(document).ready(function() {
  var $divContainer = $('.container #minhaDiv');

  $divContainer.append('<div class="elem um">Um</div>');
  $divContainer.append('<div class="elem dois">Dois</div>');
  $divContainer.prepend('<div class="elem tres">Três</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="placeholder">Placeholder</div>
  <div id="minhaDiv">

  </div>
</div>

  • It’s not exactly what I needed, but it will work. Thank you.

0

Try to do with the :last-child after the .placholder:

$(".container").find(".placeholder").append("<div class='um'>Um</div>")
$(".container").find(".placeholder:last-child").append("<div class='dois'>Dois</div>")
$(".container").find(".placeholder:last-child").append("<div class='tres'>Tres</div>")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <div class="placeholder">Placeholder</div>
</div>

  • In this case the Divs you are adding are getting inside the div placeholder, they have to stay outside. The @Pedro response got simpler. Thanks anyway! : D

  • True, the @Pedrocamarajunior response is better in this case. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.