Execute function after a dynamic div is loaded

How do I make a JavaScript execute after a div section on the page is loaded? By using only standard JavaScript.

Here is the div section in question, extracted from (https://hera-warm-demo.mybigcommerce.com/checkout):

<div aria-busy="false" class="checkout-view-content checkout-view-content-enter-done">
  <div class="loading-skeleton">
      <form class="checkout-form" data-test="payment-form" novalidate="">
        <fieldset class="form-fieldset">
          <div class="form-body">
            <ul class="form-checklist optimizedCheckout-form-checklist">
              <li class="form-checklist-item optimizedCheckout-form-checklist-item form-checklist-item--selected optimizedCheckout-form-checklist-item--selected">
                <div class="form-checklist-header form-checklist-header--selected">
                  <div class="form-field">
                    <label for="radio-bigpaypay" class="form-label optimizedCheckout-form-label">
                      <div class="paymentProviderHeader-container">
                        <div class="paymentProviderHeader-nameContainer" data-test="payment-method-bigpaypay">
                          <div aria-level="6" class="paymentProviderHeader-name" data-test="payment-method-name" role="heading">Test Payment Provider</div>
                        <div class="paymentProviderHeader-cc">
                          <ul class="creditCardTypes-list"></ul>

This section is the last section on the page, and it only loads when the customer clicks “Continue” button from the previous section.

Here is the code I tried which didn’t work… I was expecting the JavaScript to execute after “checkout-view-content” div is loaded.

Note that I cannot include the script in the dynamically loaded HTML markup, I can only inject a JavaScript code.

document.getElementsByClassName("checkout-view-content").addEventListener("DOMContentLoaded", (event) => {
document.querySelector('label[for="radio-bigpaypay"] .paymentProviderHeader-cc').style.visibility = "hidden";

Can you modify the code that dynamically loads that HTML? If so, the thing to do would be to tie your code into that after it populates the new HTML.

If not, you could explore using MutationObserver to monitor the DOM for changes.

1 Like

So… when the customer pushes a button… You load the content…

And you can’t action this change in that code? Is this a CMS thing? Wordpress or something?

Right, it’s BigCommerce and I can’t access the theme files for now, so the only way I can do that is through injecting a JS code.

So you need to add your evenlistener to the parent element you add the new code to and test in the even handlers code if the target element is the one with the checkout-view-content class

I got it working guys, thanks!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.