How do I use vanilla JS to create my own syntax highlighting for my html code elements?

How do I use pure JS to add syntax highlighting to my html <code> elements that will depict JS code?

Well, I’m just pulling this out of my butt, but…

If you’re loading it as HTML you’re parse the DOM to find those elements and then overwrite them. Then you have to grab that “code” inside that element and parse that. First you have to know what language it is. Then you have to parse that language to figure out the syntax function of every part of it - I imagine there is some kind of AST parser or something you could use? Then you’d have to rewrite your code with a bunch of HTML and CSS so that it will render the way you want.

That seems complicated. There are libraries that will do that for you. You could dissect their code to figure out what they are doing. Or you could just use their library.


There are some videos on building or implementing code highlighters here.


I think that a built-in html, css, or JS code for this purpose would be a great update and is needed. I mean why would the creators of these languages not include something so crucial? Did they not intend for them to be self-sufficient?

They are set up for that. Code highlighting is a thing specific to a program on a specific operating system. No language is that: a code highlighter is something that parses the code and interprets the structure in some system-graphics specific way.

I’m not sure what you mean by “crucial”. If I were writing a new computer language, I don’t know that writing a code highlighter for it would be even on my radar. Even for a common language, that would be useful on what, less than 0.01% of the web sites out there? And it would still have to be an add on library because you can’t expect every browser to package up all of these code highlighters for hundreds of language, for (again) the extremely small pecentage of sites that need t talk about that coding language.

No, the way this would have to work is that if people feel the need, someone will write a library. If they’re nice, they’ll publish that library. I showed you how to find some.


It’ll be a major endeavour and I doubt you’ll get a comprehensive answer here.

If you just want syntax highlight I’d recommend using an existing library such as Prism (

If you are asking for learning’s sake, you can read those existing libraries’ source code, though depending on your level of experience, this can be a very inefficient way of learning.

No it’s not crucial at all, and I apologies for the bluntness.


This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.