Search code examples
javascriptjquerytinymce

Add "rel"-attribute to img tag in TinyMCE 5 editor


I search a solution to add automatically a "rel-attribute" to every image which is added in the TinyMCE 5 editor. So the html tag should look like:

<img class="imageborder" src="https://xy.jpg" rel="lightbox" width="500" height="333" />

I've tried it like that, but it doesn't get added. This is the JSFiddle.

tinyMCE.init({
    selector: '#myTextarea',
    plugins: 'code image autolink link lists charmap print preview textcolor',
    toolbar: 'code image link | undo redo | insert | ',
    menubar: false,
    min_height: 300,
    image_class_list: [
        { title: 'imageborder', value: 'imageborder' },
    ],
    image_rel_list: [
        { title: 'lightbox', value: 'lightbox' },
    ],
    setup: function (ed) {
        ed.on("keyup", function () {
            $('#preview').html(tinymce.activeEditor.getContent());
        });
    }
});

Solution

  • You can get the img element on NodeChange event.

    Doc: https://www.tiny.cloud/docs-4x/advanced/events/#nodechange

    Jsfiddle: https://jsfiddle.net/aswinkumar863/L48jdqzs/

    tinyMCE.init({
      ...
      setup: function(ed) {
        ed.on("keyup", function() {
          $('#preview').html(tinymce.activeEditor.getContent());
        });
        ed.on('NodeChange', function(e) {
          e.element.parentNode.querySelectorAll('img:not([rel=lightbox])').forEach(img => {
            img.setAttribute('rel', 'lightbox');
          });    
        });
      }
    });