Sling Academy
Home/JavaScript/Highlighting Code Snippets: Simple JavaScript DOM Approaches

Highlighting Code Snippets: Simple JavaScript DOM Approaches

Last updated: December 12, 2024

When developing web applications, highlighting code snippets on your website can significantly enhance readability and make your examples more engaging for users. One of the common approaches to achieve this is through JavaScript manipulation of the DOM (Document Object Model), which is an essential aspect of web development.

In this article, we'll explore simple JavaScript approaches to highlight code snippets within your HTML documents, ensuring you're equipped with the necessary tools to make your code visually appealing and understandable.

Understanding the Basics

Before diving into JavaScript, let's understand the structure of HTML used for code snippets. Generally, code snippets are enclosed within the <code> HTML tag, which is often placed inside a <pre> tag to maintain formatting. For example:

<pre>
  <code>console.log("Hello, World!");</code>
</pre>

Highlighting with JavaScript

Let's proceed with using JavaScript to enhance the appearance of such code snippets. We will utilize the ability of JavaScript to traverse and manipulate the DOM.

Basic Highlighting Strategy

The following JavaScript code can be used to apply a simple background color to all <code> tags:

document.querySelectorAll('code').forEach(function(block) {
  block.style.backgroundColor = '#f0f0f0';
  block.style.borderRadius = '5px';
  block.style.padding = '10px';
});

The above script selects all code blocks and applies some basic styling to improve their visuals by giving them a light grey background, rounded corners, and padding for better spacing.

Adding Syntax Highlighting

For more sophisticated syntax highlighting, you might want to use libraries like Prism.js or Highlight.js. These libraries are designed to detect various programming languages in the <code> tags and process the contents to render highlighted code.

Here's a basic way to include Highlight.js in your project:

  1. Include Highlight.js: Add Highlight.js library into your HTML document by including the CDN link in your <head> section.
<link rel="stylesheet"
  href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.4.0/styles/default.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.4.0/highlight.min.js"></script>
  1. Initialize Highlight.js: After loading your DOM content, initialize Highlight.js with the following script.
document.addEventListener('DOMContentLoaded', (event) => {
  document.querySelectorAll('code').forEach((block) => {
    hljs.highlightBlock(block);
  });
});

This setup enhances each code block by detecting the language and applying styling accordingly, improving the comprehension and aesthetic appeal of your code examples.

Conclusion

Highlighting code snippets is made easy with JavaScript and the assistance of open-source libraries like Highlight.js and Prism.js. By applying basic and advanced techniques, you can ensure that your code stands out and is easy to understand for your audience. This foundational skill not only improves the UI of web applications but also enriches the learning experience for users engaging with your content.

Whether you choose to go with a simple styling approach or decide to include third-party libraries, remember that making code readable and attractive goes a long way in effective communication with your audience. Experiment with these JavaScript methods and see which fits your project's needs the best.

Next Article: Detecting Touch vs Click Events for Mobile-Friendly Pages in JavaScript

Previous Article: Building a Rating System with Stars Using the JavaScript DOM

Series: JavaScript: Document Object Model Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration