I want to offer code examples and I am using a JS code highlighter with an ID. See this URL for the working demo: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_syntax_highlight
I want to use this for multiple examples but the ID only works once. I have tried both ID and Class but this still doesn’t work.
w3CodeColor(document.getElementById("myDiv")); // only works for 1 element
w3CodeColor(document.getElementByClassName("myDiv")); // does not work
The example code what I have tried is below,
<div class="myDiv">code example goes here</div>
<div id="myDiv">code example goes here</div>
Any help would be much appreciated, thanks
Jay1981 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
The W3Schools library is badly designed in so much as it expects only a single element to be provided to it. getElementsByClassName()
returns a collection, so is not compatible.
To fix this you will need to loop through every .myDiv
element and call w3CodeColor()
on them individually.
document.getElementByClassName("myDiv").forEach(div => w3CodeColor(div));
However, a much better approach would be to use a different, better written library which does syntax highlighting much more effectively – for example https://highlightjs.org/