I have just started learning HTML, CSS and jQuery and I am new. I searched for binding event handlers to dynamically added elements and I found out I have to use the parent of the dynamic element as the static selector and add the dynamic element after the event method ( Correct me if I am wrong).
$(staticAncestors).on(eventName, dynamicChild, function() {});
But I do not know why the code below does not work when I change :
$("#p1")with$(this)
or$(document)with$("div")
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("div").click(function(){
$(this).html('<p id="p1" style="background: red;">Paragraph one</p> <p>Paragraph two</p>').css('margin', '15px 15px 15px 15px');
});
$(document).on('click', '#p1', function(){
$("#p1").css('background-color', 'blue');
});
});
</script>
</head>
<body>
<div> It's a div. </div>
</body>
</html>
console.log(this.id);shows that the handler is running. But for some reason the CSS isn't changing.