Highlight a text, every time page loads with JavaScript

To highlight text every time a page loads in JavaScript, you can use a for loop to iterate through words and wrap specific words in <span> elements with CSS classes for styling.

Approach

The technique involves:

  • Getting the text content using getElementById()
  • Splitting the text into an array of words using split(" ")
  • Looping through each word to find matches
  • Wrapping matching words with <span class="colorName"> tags
  • Rejoining the array and updating the HTML content

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Text Highlighting on Page Load</title>
    <style>
        .yellow {
            color: yellow;
            font-weight: bold;
        }
        .blue {
            color: blue;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <h1 id="pageLoads">My yellow Words, your blue Words</h1>
    
    <script>
        var ids = document.getElementById("pageLoads");
        var loadColorWords = ids.innerHTML.split(" ");
        
        for(var i = 0; i < loadColorWords.length; i++) {
            if(loadColorWords[i] == "blue" || loadColorWords[i] == "blue,") {
                loadColorWords[i] = "<span class='blue'>" + loadColorWords[i] + "</span>";
            }
            if(loadColorWords[i] == "yellow") {
                loadColorWords[i] = "<span class='yellow'>" + loadColorWords[i] + "</span>";
            }
        }
        
        ids.innerHTML = loadColorWords.join(" ");
    </script>
</body>
</html>

How It Works

When the page loads, the JavaScript code:

  1. Gets the element: document.getElementById("pageLoads") retrieves the target element
  2. Splits the text: innerHTML.split(" ") converts text into an array of words
  3. Loops through words: The for loop checks each word for matches
  4. Wraps matches: Matching words get wrapped in <span> tags with CSS classes
  5. Updates content: join(" ") reconstructs the text and updates the HTML

Enhanced Example with Multiple Words

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multiple Word Highlighting</title>
    <style>
        .highlight-red { color: red; background-color: #ffeeee; }
        .highlight-green { color: green; background-color: #eeffee; }
        .highlight-blue { color: blue; background-color: #eeeeff; }
    </style>
</head>
<body>
    <p id="textContent">This JavaScript tutorial shows how to highlight important words automatically</p>
    
    <script>
        function highlightWords() {
            var element = document.getElementById("textContent");
            var words = element.innerHTML.split(" ");
            
            var highlightRules = {
                "JavaScript": "highlight-red",
                "tutorial": "highlight-green", 
                "important": "highlight-blue"
            };
            
            for(var i = 0; i < words.length; i++) {
                var word = words[i];
                if(highlightRules[word]) {
                    words[i] = "<span class='" + highlightRules[word] + "'>" + word + "</span>";
                }
            }
            
            element.innerHTML = words.join(" ");
        }
        
        // Run when page loads
        highlightWords();
    </script>
</body>
</html>

Key Points

  • Automatic execution: Place the script at the bottom of the body or use window.onload
  • Case sensitivity: Word matching is case-sensitive by default
  • Punctuation handling: Consider punctuation when matching words (e.g., "blue," vs "blue")
  • Performance: For large texts, consider using more efficient methods like regular expressions

Conclusion

This technique provides an effective way to automatically highlight specific words when a page loads. The approach is flexible and can be extended to highlight multiple words with different styles using CSS classes.

Updated on: 2026-03-15T23:18:59+05:30

357 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements