Skip to content

how can you make html coming from .after() come out as inline elements

how is it possible to make html divs inline each time a new element is created using the .after() function in js , I current have a button that creates a new div, only problem is it creates it under the first div in my container and continues like this in a block layout rather than inline

js

$("button.add_item").on("click", function() {
let item_count = $('.container .compare_card').length;
$(".row:last").after(
  `         <div class="row form_row">
                <div class="col mb-4">
                        <h5>Item</h5>
                    <div class="card form_card">
                        <div class="card-body compare_cardbody">
    
                            <textarea name="ingredients" id="" cols="30" rows="10"></textarea>
                            
                        </div>
                    </div>    
                </div>
            </div>
            `
);
})
})

html

<div class="container">
  <div class="row row-cols-1 row-cols-md-2 mx-auto">
    <form action="{% url 'compare_ingredients' %}" method="post" id="compare">
      {% csrf_token %}
      <div class="row form_row">
        <div class="col mb-4">
          <h5>Item 1</h5>
          <div class="card form_card">
            <div class="card-body compare_cardbody">
              <textarea name="ingredients" id="" cols="30" rows="10"></textarea>
            </div>
          </div>
        </div>
        <div class="col mb-4">
          <h5>Item 2</h5>
          <div class="card form_card">
            <div class="card-body compare_cardbody">
              <textarea name="ingredients" id="" cols="30" rows="10"></textarea>
            </div>
          </div>
        </div>
      </div>
      <br>
      <button type="submit" class="btn btn-info">Submit</button>
    </form>
  </div>
</div>

looks like this you can see the bottom 2 divs are the newly created elements using .after() in js:

enter image description here

Answer

You are adding a new row on each click. If you want a new column, you’ll need to check if you should be appending a column to an existing row or creating a new row and adding to that.

if ($("#compare > .row:last > .col").length === 2)
{
  $("#compare").append('<div class="row form_row"></div>');
}

    $("#compare > .row:last").append(
        `
            <div class="col mb-4">
                    <h5>Item</h5>
                <div class="card form_card">
                    <div class="card-body compare_cardbody">

                        <textarea name="ingredients" id="" cols="30" rows="10"></textarea>
                        
                    </div>
                </div>    
            </div>
        `
            );
           })