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

Acquiring an element through ViewChild() within Angular

I am in need of a table element that is located within a modal. Below is the HTML code for the modal and my attempt to access the data table, which is utilizing primeng. <ng-template #industryModal> <div class="modal-body"> <h4>{{&a ...

Clicking on the button will result in the addition of new

Having some trouble with jQuery as I try to dynamically add and remove HTML elements (on click of +) while also making sure each element has a unique name and ID like "name_1", "name_2"... Unfortunately, things aren't quite going as planned. Below i ...

How come when utilizing jQuery to call a PHP function, the output received is the actual PHP code?

I'm currently working with a php file that has the following code: if(isset($_GET['fn'])) { if($_GET['fn']=='generarxml') generarxml(); else exit; } function generarxml() { ...

changing pictures with jquery

Struggling with this code snippet: $('#clicked_package').css({"background-image" : "url(img/head_2.png)"}).fadeOut("slow"); $('#clicked_package').css({"background-image" : "url(img/head_2_normal.png)"}).fadeIn("slow"); No matter which ...

Revitalize website when submitting in React.js

I need assistance with reloading my React.js page after clicking the submit button. The purpose of this is to update the displayed data by fetching new entries from the database. import React, {useEffect, useState} from 'react'; import axios from ...

Managing events inside a JQuery dialog box

Currently, I have successfully implemented a JQuery dialog that allows users to change their password. The functionality works smoothly as the system checks if the two passwords match and if the new password meets the minimum requirements before making an ...

Using AJAX to inject JSON data from PHP into Edge Animate

For a school assignment, I am currently working on a project using edge animate. My objective is to import data from a database hosted on my school's webspace and incorporate it into the edge animate project. Despite researching online for a solution ...

Using ng-include destroys the styling of the dropdown menu in a bootstrap ul li format

Greetings! I am attempting to replicate the following code snippet that creates a basic dropdown menu using bootstrap: <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="fal ...

Creating an Asynchronous REST API in Laravel without using Ajax is another alternative

I am revisiting Laravel and looking to explore alternatives to using Ajax for asynchronous rest services. Can anyone recommend different libraries that I could use for this purpose? ...

Firebase functions are giving me a headache with this error message: "TypeError: elements.get is not

Encountering the following error log while executing a firebase function to fetch documents and values from the recentPosts array field. Error: Unknown error status: Error: Unknown error status: TypeError: elements.get is not a function at new HttpsEr ...

The JavaScript file fails to load when accessing port 8080

As I embark on my journey into backend development, please bear with me. Currently, I am working on a JavaScript program that retrieves text data from my localhost. I have set up an HTTP server using Node.js which serves as a regular HTTP server. The serve ...

Error: The function Stripe.customers.cancel is not recognized in Stripe version 14.18.0

When executing Cypress tests that involve calling a cleanup function to remove users in Stripe, I encounter the following error: Body: { "status": 500, "message": "Error while cleaning the stripe test data", "error" ...

Exploring the world of Node.JS and AngularJS through the integration of API routes

Currently, my backend is built using Node.JS with Express and serving as my API servlet. On the frontend, I'm utilizing AngularJS for the user interface. After numerous searches on Google, I was able to resolve an issue where I faced challenges using ...

What is the best way to arrange this by DateTransaction using a dropdown list?

Requesting assistance from the PHP community! I'm a newbie and in need of your expertise. My task is to create a dropdown list that sorts a table based on the DateTransaction column, with options ranging from January to December. Here is the code sni ...

What could be causing my image not to show up on ReactJS?

I'm new to ReactJS and I am trying to display a simple image on my practice web app, but it's not showing up. I thought my code was correct, but apparently not. Below is the content of my index.html file: <!DOCTYPE html> <html> & ...

Utilizing the state as a condition within the useEffect to update the component

Is there a way to automatically hide the mobile menu when the URL changes in ReactRouter? I have noticed that I get a warning for not tracking mobileOpen as a dependency, but strangely the code still works fine. const Navbar: React.FC<Props> = props ...

What is the best way to retrieve every single element stored in an Object?

On a particular page, users can view the detailed information of their loans. I have implemented a decorator that retrieves values using the get() method. Specifically, there is a section for partial repayments which displays individual payment items, as d ...

Tips for iterating through an associative array/object within a MongoDB schema instantiation using mongoose without the need to specify schema configuration parameters

I've been searching on Google for hours without finding a clear answer. Perhaps I need to adjust my search terms? Here's my question: I'm a beginner with MongoDB and I'm trying to modify the values of a schema instance before saving it ...

What are the steps to implement the "render" function from one class into another class within three.js?

As a newcomer to three.js, I have been working on creating a bowling game. However, I am encountering an issue where I need to access a function from my "Application" class within the physics class that I have created. Here is a snippet of the Application ...

A stationary webpage nested within a lively pathway on NuxtJS

I have a Nuxt app with a list of cars available at: /cars. You can select a specific car at /cars/:id. I would like to have a toolbar that routes to different views such as: /cars/:id/routes, /cars/:id/drivers, etc. Within the /cars/:id page, I have creat ...