Search code examples
javascriptjquerywordpressadvanced-custom-fieldswordpress-gutenberg

jquery inside wordpress ACF custom block can't select element outside of block


I have an advanced custom fields gutenberg block template like this:

<article class="m04x">
    <hr>
    <div class="row">
        <div class="col-md-12">
            <h4>On this site:</h4>
            <ol id="anchor_list">
            </ol>
        </div>
    </div>
</article>

<script>

    (function($) {
        var anchor_list = $('#anchor_list');
        $('.anchor-block').each(function() {
            var heading_text = $(this).html();
            var href = '#' + $(this).attr('id');
            var html = '<li class="nav-item"><a class="fontstyle" href="' + href + '">' + heading_text + '</a></li>';
            anchor_list.append(html);
        });
    })(jQuery);

</script>

Registered using:

function register_on_this_site_block() {
    if ( function_exists( 'acf_register_block' ) ) {
        acf_register_block(array(
            'name'            => 'on-this-site-block',
            'title'           => __( 'On This Site Block', 'wds'),
            'description'     => __( 'Links to parts of current page.', 'wds'),
            'render_template' => get_template_directory() . '/template-parts/blocks/on_this_site.php',
            'category'        => 'layout',
            'icon'            => 'align-center',
            'mode'            => 'preview',
            'keywords'        => array('links'),
        ));
    }
}
add_action( 'acf/init', 'register_on_this_site_block' );

JQuery can select the '#anchor_list' seemingly because it is in the same template. But when selecting the '.anchor-block' it returns an object with length 0 and the 'each' function does nothing.

How can I access elements outside of this block? Actually it should be mentioned that the '.anchor-block' element resides in another custom ACF block.


Solution

  • As Taplar said, the elements I was selecting did not exist at the time I was trying to select them. I thought my (function($) { })(jQuery) function was running after the page has been fully loaded but actually it does not. I changed the code to this and it works:

        var $ = (jQuery);
        $(window).bind("load", function() {
            var anchor_list = $('#anchor_list');
            $('.anchor-block').each(function() {
                var heading_text = $(this).html();
                var href = '#' + $(this).attr('id');
                var html = '<li class="nav-item"><a class="fontstyle" href="' + href + '">' + heading_text + '</a></li>';
                anchor_list.append(html);
            });
        });
    

    Although you can see the empty list for a split second before it populates with the <li> elements, but thats fine for me.