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

if i generated html elements using append , can i effect them using jquery after that?

i used "append" method in JQuery to generate some HTML input boxes , then 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 = "txt/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>