Shkelqim Maxharraj Shkelqim Maxharraj - 3 months ago 6
CSS Question

Edit respective element on list

I'm making 2 lists. List of boys and girls. The button creates new element for each. Soo I want when i click for example boy1 element. Edit girl1 element. And change the color to black. When i click boy 2 edit girl2 and so on.
This is my Html

<div class="mainDiv">
<input type="button" value="Add new" id="clickme"onclick="addElements()">
<ul id="boys">
<li id="boy1">Boy1</li>
</ul>

<ul id="girls">
<li id="girl1">Girl 1</li>
</ul>
</div>


Css

#boys {
color:red;
}
#girls {
color:blue;
}
li {
cursor:pointer;
}


And JavaScript

var i = 1;
$("#clickme").click(function() {
i++
$("#boys").append("<li id='boy" + i+"'>Boy"+ i +"</li>");
$("#girls").append("<li id='girl" + i+"'>Girl"+ i +"</li>")
});


The example of result should look like this

enter image description here

Answer

You need to delegate event on the parent div:

$(function () {
  var i = 1;
  $("#clickme").click(function() {
    i++
    $("#boys").append("<li id='boy" + i+"'>Boy"+ i +"</li>");
    $("#girls").append("<li id='girl" + i+"'>Girl"+ i +"</li>")
  });
  
  // attach event handler for all li elements: also for
  // the one created dynamically
  $('div.mainDiv').on('click', 'li', function(e){
    if (this.id.indexOf('boy') != -1) {
      $('#girl' + this.id.substr(3)).css("color", "black");
    } else {
      $('#boy' + this.id.substr(4)).css("color", "black");
    }
  });
});
#boys {
  color:red;
}
#girls {
  color:blue;
}
li {
  cursor:pointer;
}
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<div class="mainDiv">
    <input type="button" value="Add new" id="clickme">
    <ul id="boys">
        <li id="boy1">Boy1</li>
    </ul>

    <ul id="girls">
        <li id="girl1">Girl1</li>
    </ul>
</div>