highlightjs / highlight.js

JavaScript syntax highlighter with language auto-detection and zero dependencies.
https://highlightjs.org/
BSD 3-Clause "New" or "Revised" License
23.54k stars 3.58k forks source link

[Request] `highlightAll(element)` #4092

Open samueller opened 4 weeks ago

samueller commented 4 weeks ago

I display dynamic messages on my webpage that sometimes have code snippets within those messages. highlightElement(element) doesn't work on the message node because most (sometimes all) of the message is not a code snippet, the code snippets are nested inside. So I do a highlightAll() repeatedly. I know I could cycle through all the <pre><code>s within a message and run highlightElement(element) for each.

It seems like highlightAll() should take an optional element that it would be applied to. In my case, I'd apply it to the incoming message that may have 1 or more code snippets nested inside.

joshgoebel commented 4 weeks ago

So I do a highlightAll() repeatedly. ..... It seems like highlightAll() should take an optional element

If highlightAll already works, why do you suggest the additional parameter? Is it scoping you're looking for - only pre/code blocks inside some other element?

I could cycle through all the <pre><code>s within a message and run highlightElement(element) for each.

Generally we try to cover the 95% use case and anything else that a user could easily implement easily with JS we prefer to not add to the core library. It sounds like what you want is easily achieved with a tiny helper function and built-in DOM methods.

If you wanted to build this and share it on the wiki or publish a plugin, that'd be awesome.

samueller commented 4 weeks ago

It is scoping I'm looking for. And potentially a performance improvement (although the improvement might be negligible). In my case, I may get streams of messages containing nested code blocks entering my webpage. Applying highlight to each new code block instead of to all code blocks is much preferred.

The following simple code I wrote does the job:

const highlightAllElement = el => el.querySelectorAll('pre code').forEach(hljs.highlightElement)

It's not a plugin, should I just share it as a new page in the wiki?

joshgoebel commented 4 weeks ago

Sure.