Just easy highlighting using tags in Javascript

I have come across a code snippet that seems to be functioning well:

    <html>

    <head>

    <title>Testing JS Highlighting</title>

    <script type="text/javascript">

    function highlight()
    {
            var t = document.getElementById('highlight').innerHTML;

            t = t.replace(/(if|switch|for|while)\s*(\()/gi, "<b>$1</b>$2");
            document.getElementById('highlight').innerHTML = t;
    }

    </script>

    </head>

    <body onload="javascript:highlight();">

    <pre id="highlight">
    1  if(foo) {
    2          bar();
    3  }
    4
    3  while(--baz) {
    5          oof();
    6  }
    </pre>

    </body>

    </html>

Instead of targeting just one specific <pre> tag with an ID, I am interested in applying this functionality to all the <pre> tags on the page. It would be ideal to combine a specific tag with a unique identifier. Is there a way to enhance the existing JavaScript function to achieve this by maybe using

document.getElementsByTag(tag).getElementsById(id).innerHTML
or similar method in a loop? I attempted it myself but didn't get desired results. I am seeking a simple solution without anything too complex.

Looking forward to your suggestions.

--
nkd

Answer №1

You were so close to getting it right ;-)

function handleAllPreElements() { 
    var pres = document.getElementsByTagName("pre");
    for (var i = 0; i < pres.length; i++) { 
        // You can verify the class name with pres[i].className === "highlight"
        // (and it's better to use a class instead of an id)
        if (pres[i].className.indexOf("highlight") >= 0) {
            // Insert desired action here
        }
    }
}

If you utilize a JavaScript framework like jQuery, the process becomes even simpler:

$("pre.highlight").each(function(i) {
    // Insert desired action here
});

Nevertheless, employing a framework may be excessive...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A tiny blue spot popping up beside the roster of users

I'm working on a render function that displays a list of users with avatars and names. The issue I'm facing is that when the page initially loads, there's a blue dot to the left of each user. However, if I navigate to another page and then g ...

Passport.socket.io cannot resolve the issue of a missing session

The Issue I am facing a problem with the failed connection to socket.io: No session found using passport.socketio.js and I am unable to identify the root cause. Despite checking similar posts, the configuration seems fine to me. However, it appears that ...

What is the best way to switch the CSS class of a single element with a click in Angular 2

When I receive data from an API, I am showcasing specific items for female and male age groups on a webpage using the code snippet below: <ng-container *ngFor="let event of day.availableEvents"> {{ event.name }} <br> <n ...

Is it possible to extract only the time from a date and time using angular-moment library?

I am trying to display only the time from a date. My code looks like this: $scope.sample_time = "September 14th 2017, 1:00:00 pm"; What I want in my view is to show just the time, for example 1:00 pm. I attempted to use angular-moment, with something li ...

Dealing with error handling in NUXT using asyncData and Vue actions

The URL I am trying to access is http://mywebsite.com/[category that doesn't exist]. Despite the code snippet provided below, I am unable to reach the catch block in asyncData. async asyncData({ params, store }) { try { await store.dispatch(&ap ...

Ways to Conceal <div> Tag

I need help with a prank .html page I'm creating for a friend. The idea is that when the user clicks a button, a surprise phrase pops up. I have managed to hide and unhide the phrase successfully using JavaScript. However, my issue is that when the pa ...

Why does Vuetify/Javascript keep throwing a ReferenceError stating that the variable is undefined?

I'm currently developing in Vuetify and I want to incorporate a javascript client for Prometheus to fetch data for my application. You can find the page Here. Despite following their example, I keep encountering a ReferenceError: Prometheus is not def ...

JavaScript Hangman Game Malfunctioning

I am in the process of creating a basic hangman game to be played on a web browser. Whenever the user clicks a button, it triggers a function called pickWord(): <button onclick="pickWord()" id="restart">Choose A Word</button> This functi ...

Utilize the power of jQuery for form validation by combining the errorPlacement and showErrors functions

I am currently attempting to implement validation using the Jquery .validate plugin. Unfortunately, I have encountered an issue where I am unable to utilize both the errorPlacement and showErrors methods simultaneously. If you'd like to see a demons ...

How to drag an item onto another element using Vue.Draggable without the need for adding or removing

Are you familiar with the library https://github.com/SortableJS/Vue.Draggable? I am trying to achieve a drag and drop functionality where I can drag a file into a folder. However, I am facing an issue as the @change event only provides data about the drag ...

Troubleshooting Event.target Problem in Firefox 6

When working in Firefox 6, I encountered an issue while trying to identify the target element on which the event occurred. Instead of displaying the desired element, it was showing as undefined in the alert message. Utilizing the Firebug tool for debugging ...

Ionic, Angular - A component with two out of three inputs displaying undefined values

I am facing an issue with the @input() in my code. Two out of three inputs have undefined values when I try to use them, although they can be displayed using interpolation in the template file. .ts : export class NoteCanvasPageComponent { @Input() note ...

Ways to modify babel output file extensions

I'm facing an issue where babel --out-file-extension is not working as expected. Below is my package.json : { "name": "Assets", "version": "1.0.0", "description": "", "main" ...

Positioning a material UI dialog in the middle of the screen, taking into account variations in its height

Dealing with an MUI Dialog that has a dynamic height can be frustrating, especially when it starts to "jump around" the screen as it adjusts to fit the content filtered by the user. Take a look at this issue: https://i.stack.imgur.com/IndlU.gif An easy f ...

Tips for effectively exchanging information among angular services

Currently, I am in the process of refactoring a complex and extensive form that primarily operates within a controller. To streamline the process, I have started segregating related functions into separate modules or services. However, I am grappling with ...

The frequency of database updates exceeds expectations - involving vue.js this.$router.push and express operations

Having some trouble updating a MongoDB with this code. It seems to be updating three times instead of just once due to having three dates in the posts.date field. Utilizing Vue, Mongo, and Express for this project, I have the following data structure: { ...

Executing the Angular 2 foreach loop before the array is modified by another function

Currently, I am facing some difficulties with an array that requires alteration and re-use within a foreach loop. Below is a snippet of the code: this.selectedDepartementen.forEach(element => { this.DepID = element.ID; if (this.USERSDepIDs. ...

Incorporating a parameter into a <div> only when the parameter holds a value

Being new to web development, I have a rather basic query. If the datainfo prop variable is not empty, I'd like to include a data attribute in the div tag. <div style={{height: props.height - handleHeight()}} data={datainfo ? datainfo : ""}> C ...

What is the preferred method for verifying AJAX success when the server's response is either true or false?

My server response can be either true or false. I've been attempting to determine how to check for success based on the returned value being true or false using the script below: $('form[data-async]').on('submit', function(event) ...

Unexpected absence of Aria tags noticed

I've been working on integrating ngAria into my project. I have injected it into my module and created the following HTML: First Name: <input role="textbox" type="text" ng-model="firstName" aria-label="First Name" required><br> Employee: ...