inaz inaz - 3 months ago 6
CSS Question

How to append div for each div

i have a list that i want to append each div when i click in "add".
it works but every time that i click on "add" it works for all of my divs. i want to attend new div only for each div that i click.
Here is my code:



$(".add").click(function() {
$(".content").append('<ul class="pricepart"><li><input type="text" /></li></ul>');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
<ul class="pricepart">
<li>
<input type="text" />
<span class="add">ADD+</span>
</li>
</ul>
</div>
<div class="content">
<ul class="pricepart">
<li>
<input type="text">
<span class="add">ADD+</span>
</li>
</ul>
</div>




Answer

Because you are just applying the method to class and where ever it find the class the function will be executed.

You need to define that function should be executed on the parent class of the click element.

You can use .parents() or .closest() selector for the same like this

$(".add").click(function () {
  $(this).closest(".content").append('<ul class="pricepart"><li><input type="text" /></li></ul>');
});

OR

$(".add").click(function () {
  $(this).parents(".content").append('<ul class="pricepart"><li><input type="text" /></li></ul>');
});

Sometime .parents() creates issue if there is multilevel inheritance with same classes but in this case it will also work fine

Comments