Access Customizer’s DOM – jQuery

The customizer preview is in a different window than the window that contains the customizer controls. Specifically, the customizer preview is contained inside of an iframe. So that is why you cannot directly use jQuery to select elements. One way to work around this is to use parent.jQuery from the preview, but this is not recommended since the customizer preview may in fact be on a separate domain entirely and such a call would violate the same-origin policy in the browser. Therefore, if you’re wanting to interact with the controls from the preview, what you need to do is pass messages from the preview to the pane. Examples of this can be seen in core actually, specifically in customize-selective-refresh.js where it sends the focus-control-for-setting message and then in customize-controls.js where it receives this message. Here is a standalone example and how to obtain the root jQuery container for a given control when you mouse over the site title.

Enqueue this script at the wp_enqueue_scripts action if is_customize_preview(), and let it have the customize-preview script as its dependency:

// customize-preview-example.js
(function( api, $ ) {
    api.bind( 'preview-ready', function() {

        $( '.site-title' ).on( 'mouseover', function() {
            api.preview.send( 'site-title-mousedover', 'some optional message value' );
        } );

    } );
}) ( wp.customize, jQuery );

And then this script that runs in the controls (parent) window which depends on customize-controls and is enqueued at the customize_controls_enqueue_scripts action:

// customize-controls-example.js
(function( api ) {
    api.bind( 'ready', function() {

        // Wait for the site title control to be added.
        api.control( 'blogname', function( siteTitleControl ) {
            api.previewer.bind( 'site-title-mousedover', function( message ) {
                console.info( 'Message sent from preview:', message );
                console.info( 'The jQuery container element for the site title control:', siteTitleControl.container );
            } );
        } );
    } );
}) ( wp.customize );

This being said, be wary of using jQuery to manipulate controls. The customizer controls are tied to their associated customizer settings. If you want to make a change to the value shown in a given control’s input, you need to modify the setting associated with it, not modify the control’s input directly. Also, if you want to hide a control then what you’re looking for is the active_callback on the added control.

Leave a Comment