简体   繁体   中英

Add class to dynamically generated HTML

I'm working to use custom checkbox styles with a checkbox which is dynamically generated by javascript for the Google Identity Toolkit. For example, we add this div:

<div id="gitkitWidgetDiv"></div>

And the Google Identity Toolkit script generates new html for that div.

I need to add a class to the HTML which is added by the javascript without any action by the user and I'm struggling to make it work. For example, here is my code:

$("#gitkitWidgetDiv").on('ready', ".gitkit-sign-in-options label", function() {
    $(this).addClass('checkbox');
});

I've tried switching 'ready' for a few other options and also using the livequery plugin, but nothing is working for me. It works if I use an active event like 'click,' but I can't figure out how to do this when the page loads. Could someone please help? Thanks!

Modern browsers (including IE11) support mutation obervers . You can use one to monitor the parent node of the div that will be added. When the div has been added, just add the class.

Here's something I made which comes in handy in annoying cases like this where it's difficult to tell when the element you need has finished loading in: https://gist.github.com/DanWebb/8b688b31492632b38aea

so after including the function it'd be something like:

var interval = 500,
    stopTime = 5000,
    loaded = false;
setIntervalTimeout(function() {
    if($('.dynanicElementClass').length && !loaded) {
       $('.dynanicElementClass').addClass('checkbox');
       loaded = true;
    }
}, interval, stopTime);

It's not perfect and I'm sure there are better solutions out there but in most cases like this it does the job.

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