user2720708
user2720708

Reputation: 495

Insert an element after a div

I'm having a problem on how to insert a generated element to a specific div. For more clearer view I have this hierarchy of elements

<div class="mod-attr-holder" id="chosen-product-16">
  <div class="attr-holder">...</div>
  <button class="btn btn-lg btn-addcart btn-bw-orange button-cart" style="width: 90%;" data-id="chosen-product-16">...</button>
  <a class="btn fontsize18 btn-wishlist text-center">...</a>
  <div class="attr-holder">...</div>
  <input type="hidden" id="option-45" name="option[45]" value="126">
</div>

Now I have a button that after clicked it has to insert in that specific div which is after the div.class="attr-holder". After insert it must look like this:

<div class="mod-attr-holder" id="chosen-product-16">
  <div class="attr-holder">...</div>
  <div class="attr-holder">...</div> // this is where it has to insert the newly added element
  <button class="btn btn-lg btn-addcart btn-bw-orange button-cart" style="width: 90%;" data-id="chosen-product-16">...</button>
  <a class="btn fontsize18 btn-wishlist text-center">...</a>
  <div class="attr-holder">...</div>
  <input type="hidden" id="option-45" name="option[45]" value="126">
</div>

I have this code for now:

$('.myelement').on('click', function() {
  var product_id = $(this).data('parentid');
  $('#chosen-product-'+product_id + ' .attr-holder').append(html);
});

Upvotes: 0

Views: 257

Answers (2)

MH2K9
MH2K9

Reputation: 12039

Try using insertAfter(). You also should use :first because there exist two class by name attr-holder. Example:

$('.myelement').on('click', function() {
    var product_id = $(this).data('parentid');
    var html = '<div class="attr-holder">...</div>';
    var $selector = $('#chosen-product-'+product_id + ' .attr-holder:first');
    $(html).insertAfter($selector);
    $(this).off("click"); //To disable simultaneous click
});

Upvotes: 1

Mohi
Mohi

Reputation: 1808

You should specify and find the last or the first element which has attr-holder class then insertAfter it for example:

$('.myelement').on('click', function() {
    var product_id = $(this).data('parentid');
    var html = '<div class='attr-holder'>...</div>';
    var $selector = $('#chosen-product-'+product_id).children('.attr-holder').last();
    $(html).insertAfter($selector);
});

The new HTML tag will be added after the selector in the mod-attr-holder hierarchy

Upvotes: 0

Related Questions