How to manipulate DOM after new elements have been inserted?

I am working on a WooCommerce/WordPress site at the moment and on the checkout page, when I submit the form, it submits through Ajax and if there are errors (required fields not filled in etc), the page inserts some html and lists what fields need to be filled in.

I have some jQuery that places this newly inserted html in the page to a new place on the page but it doesn’t work.

Read More

WooCommerce code inserted on submit (if errors):

<ul class="woocommerce-error">
    <li><strong>First Name</strong> is a required field.</li>
</ul>

My Code:

var wc_errors = jQuery('ul.woocommerce-error');
jQuery('.errors_placeholder').append(wc_errors);

It might be useful also to note that my JavaScript file is loaded before the WooCommerce JavaScript file.

Related posts

Leave a Reply

2 comments

  1. Try the following:

    $(document).ready(function() {
        var wc_errors = $('ul.woocommerce-error');
        $('.errors_placeholder').appendTo(wc_errors);    
    });
    

    You need it in the $(document).ready function to tell jQuery the DOM is ready.

    Check out my example

  2. Could be done using checkout_error event.

    (function ($) {
        $(document.body).on('checkout_error', function (error_message) {
            $('.errors_placeholder').empty().html(error_message);
        });
    })(jQuery);