M-Amr Moussa M-Amr Moussa - 2 months ago 9
CSS Question

If I generate HTML elements using append, can I affect them using jQuery after that?

I used the

append
method in jQuery to generate some HTML input boxes; now I want to make some effects on those input elements using jQuery but I can't. This is a little example of what I wanna do.

<style type="text/css"></style>
<style>
.focus
{
background-color: green;
}
</style>
<script src="alu_afric/Java/java.js"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
$("#newHTML").append('<input type="text" placeholder="some text .."/>');
});
$("input").focus(function() {
$(this).addClass("focus");
});
});
</script>
<button>Click</button>
<body>
<div id="newHTML"></div>
</body>

Answer

The event listener should be

$( document ).on( 'focus', 'input[type=text]', function() {

Instead of

$("input").focus(function(){

Please check snippet for more understanding.

$(document).ready(function(){
  $("button").click(function(){
    $("#newHTML").append('<input type = "text" placeholder = "some text .."/>');
  });
  $( document ).on( 'focus', 'input[type=text]', function() {
    $(this).addClass("focus");
  });
});
.focus
 {
   background-color: green;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click</button>
<body>
  <div id = "newHTML"></div>
</body>

Comments