block editor - How to add classes and events to image in javascript using Gutenberg?

admin2025-06-05  2

Before WordPress 5.0, manipulating the content in the editor using javascript was fairly easy:

  • add_wp_tiny_mce_init_script to add your script in the TinyMCE iframe
  • profit

The script I include in TinyMCE gets all the img elements and adds an error handler onto them:

jQuery(document).ready(function($) {

    $('img').each(function(index, el) {
        var img = $(el);
        console.log(img);
        $('<img/>').on('error', function() { handleError(img); }).attr('src', img.attr('src'));
    });

    function handleError(media) {
        // do stuff
    }
}

It allows me to detect broken images (only those with a specific class), add a new class to them, change the href dynamically to show a fallback, and trigger an alert telling the editor to re-insert the image - easy.
A similar operation is done on the frontend on images with the aforementioned class to try and load a fallback as well.

Now, with WordPress 5.0, the script is included in TinyMCE (for blocks using the Classic Editor), AND on the page itself ; but that bit doesn't get the images inserted in the Gutenberg blocks:

$('img').each(function(index, el) {
    var img = $(el);
    console.log(img);
    $('<img/>').on('error', function() { handleError(img); }).attr('src', 
 img.attr('src'));
});

This is because when the script is running, the DOM is not loaded yet. I also noticed that directly manipulating the HTML rendered on the page doesn't work anyway (add a class to an image in the inspector > save post > reload > class was not saved).

What would be the proper way to:

  • add events to and manipulate attributes of images present in Gutenberg-created blocks?
  • getting these changes actually saved when the changes are submitted?
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749116535a316502.html

最新回复(0)