2

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>
inaz
  • 1,755
  • 4
  • 20
  • 41

4 Answers4

3

You have to select this clicked button parent, like this:

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

Working example: https://jsfiddle.net/k98tw1je/

Also you can use closest instead of parents

2

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

Gaurav Aggarwal
  • 9,809
  • 6
  • 36
  • 74
1

The $(".content") selects all elements with the class instead you need to get the element based on the clicked .add element for that closest() method .

$(".add").click(function () {
  // inside the handler `this` refers to the dom object of 
  // clicked element and closest can be used to find nearest
  // ancestor element
  $(this).closest(".content").append('<ul class="pricepart"><li><input type="text" /></li></ul>');
});
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

Try This-

$(".add").click(function() {
  $(this).parents().eq(2).append('<ul class="pricepart"><li><input type="text" /></li></ul>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.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>

JSFiddle

Karthikeyan Vedi
  • 1,360
  • 1
  • 11
  • 17