简体   繁体   中英

How to select dynamically added elements with Jquery

I'm loading some html using jQuery function .load() and everything works fine. The problem is that I need to select some of the dynamic created elements to apply some styles with JS. For example:

$(".new-element-class").datepicker();

I know that dynamically added elements are not part of DOM and that I can trigger events this way:

$("body").on("click", ".new-element-class", function() {});

I have read a lot of answers with that solution but that's not what I need. I want to select and apply a function without having to wait for an event. I also tried find() and it didn't work.

You need to call .datepicker() in the code that adds the new element dynamically. You can do this in the callback function of .load()

$("#element").load("url", function() {
    $(this).find(".new-element-class").datepicker();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM