To dynamically highlight certain nodes(which your code must be between <code><pre></pre></code>
) in your DOM:
hljs.highlightBlock(document.getElementById("codeblock"));
Where, codeblock
is the id of your node. For example, <code id=""codeblock><pre></pre></code>
.
What we do here is, we are using hljs
method to highlight only particular element/node in your DOM.
And you are adding and removing elements from your DOM. So, you need to check if any new element that you are intended to highlight is added or not. And call the above function to highlight the code.
To check for mutations in your DOM, you can use MutationObserver to a listen to the changes and call the above function to highlight the code.
Note: Don't use setTimeout()
to poll for changes! It effects performance of the website.
If you find MutationObserver difficult to implement, you can use this awesome library arrive.
Either download .min.js
and include it in your browser or Install the npm package of arrive
:
$ npm install -S arrive
If you are using through npm, import it in your code like require("arrive");
Write a callback function for arrive
:
highlight(){
if(document.getElementById("codeblock") != null){
hljs.highlightBlock(document.getElementById("codeblock"));
}
}
To register arrive
: Call this in your constructor()
document.arrive("#codeblock", () => this.highlight());
It should do the work.