CKEditor: alter anchor HTML output

Published by Lennart Van Vaerenbergh on August 30, 2016

Altering the html output of an anchor set by CKEditor. It appeared not to be straight forward to find documentation about this. So for future reference, here's an example.

In my case, I had to add a specific class to the anchor A-tags in order to apply some CSS to them.

Step 1 (for Drupal sites only)
First of all, as I was using Drupal, I wanted to extract the ckeditor.config.js out of the contrib module (ckeditor) and place it in my custom theme root folder. We just have to make sure to set "Load ckeditor.config.js from the theme path" to true in the CKEditor profiles we're using.

Step 2
Add the following code to the newly copied ckeditor.config.js file in our theme directory:
CKEDITOR.on('instanceReady', function (ev) {

  ev.editor.dataProcessor.htmlFilter.addRules( {
    elements : {
      a : function( element ) {
        // Add class to anchor a-tags.
        var attr = element.attributes;

        if (attr['data-cke-saved-href'] == null) {
          element.attributes.class = 'anchor-target';


We distinguish anchor a-tags from normal a-tags (read: links) by the missing href. Though (and this is the tricky part) we can't just check for the href attribute being empty, as CKEditor uses another attribute while executing this code which will then be used to set the href in the final output saved to the database. The attribute we have to check for being empty is "data-cke-saved-href". Good to know is that the HTML is altered by our script during saving of the text to the database. Not for example while displaying on the front end.

You can now add links and anchors through CKEditor and see the result on the front end.


Submitted by mnsxmasma on Monday, April 11, 2022 - 08:00
Submitted by Anonymous on Friday, May 27, 2022 - 12:50
Submitted by AfxxHaili on Monday, August 15, 2022 - 13:58
canadian pharmacies savon pharmacy cipa canadian online pharmacies

Add new comment

(If you're a human, don't change the following field)
Your first name.
(If you're a human, don't change the following field)
Your first name.
This challenge is for testing whether or not you are a human visitor and to prevent automated spam submissions.