0

$("button").on("click", function() {
  $("ul").append($("<li></li>").text("good"));
});

$("ul").on("click", "li", function() {
  $(this).remove();
});

$("ul").on("mouseenter", "li", function() {
  $(this).css("color", "yellow");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <button>click me</button>
  <li>good</li>
</ul>

Can we use objects in on() to create multiple events to elements that are yet to be created?

Magiczne
  • 1,586
  • 2
  • 15
  • 23
Nivi
  • 1
  • the question is not exactly clear, but the simple answer is yes. Perhaps, if your question is more specific, like an error or something, we could give more specific answers. – Jay Sep 25 '20 at 10:00
  • Not really sure what you mean by "*use objects in on()*" - where are you wanting to use an object? What would that object (if it's not been created yet). Can you provide an example of where you'd like to use an object? – freedomn-m Sep 25 '20 at 10:18
  • https://api.jquery.com/on/ **selector:** *string* - so no, if you want to put it in the selector (but some jquery methods work with objects where the doc says string (eg .html(obj)) so... maybe? – freedomn-m Sep 25 '20 at 10:20
  • Your code seems to do what the title is asking? As long as the parent element the `.on()` is attached to isn't dynamic, you can add a selector argument to handle to any dynamically added children. Aside from that, I'd recommend appending your html whole: `.append('
  • good
  • ')`, which will save you two method calls. Also, jQuery is chainable `$('ul').on().on().on()`. – PoorlyWrittenCode Sep 25 '20 at 10:49