Search code examples
javascriptjquerycssckeditorhighlight.js

auto detect added class in highlight.js for dynamically added elements


i am using highlight.js 9 and added it like the following

 <script src="highlight/highlight.pack.js"></script>

i am using ckeditor which adds highlight.js class on the fly.I need to append content in a div.When i append it i want highlight.js will detect which language class is used by editor and apply styles automatically when i append it to my page .How to achieve this?

say i am have the following content in my editor:

<pre>
<code class="language-css"><pre> <code>hljs.configure({useBR: true}); $('div.code').each(function(i, e) {hljs.highlightBlock(e)});</code></pre></code>

which results in the following styling:

enter image description here

when i will append it my page i want the exact same styling as i am seeing on the editor .How to do that.

a image of div id='content' currently it shows no styling :

enter image description here


Solution

  • Solved it. I had to use the following code inside onclick event handler:

     $('pre code').each(function(i, block) {
        hljs.highlightBlock(block);
    });
    

    full code:

    CKEDITOR.replace( 'editor1');
    var content = $("#content");
    function lol(event) {
    
        var el = CKEDITOR.instances.editor1.getData();
        alert(el);
        var html = $.parseHTML(el);
    
        content.append(html);
    
        $('pre code').each(function(i, block) {
            hljs.highlightBlock(block);
        });
    }