Replicating a website to use at a later time

I am brand new to the world of Javascript, currently diving into JavaScript and jQuery for an issue I'm facing.

Here's what I'm trying to accomplish:

  1. I have a selection of words ("foo", "bar")
  2. Retrieve the current webpage's content (html, css, content)
  3. I aim to refresh the page with "foo" and "bar" highlighted wherever they are found on the page.

All I want is to highlight any page that users open with a predefined set of words contained within it.

Right now, I'm struggling with step 1. Could someone kindly guide me towards an approach or resource I can study up on?

Answer №1

To add some dynamic text highlighting on a webpage, you can use the following code snippet. Let's assume we want to highlight the word "entirely":

var term = 'entirely';
var elements = document.querySelectorAll('*');
for(var j = 0; j < elements.length; j++) {
    var item = elements[j];
    if(item.innerHTML.split('<')[0].indexOf(term) > -1) {
       item.innerHTML = item.innerHTML.replace(term, '<span style="background-color: cyan">'+term+'</span>');
    }
}

Answer №2

Allow me to guide you in the right direction. While this code snippet may not be the optimal solution, it serves as an illustration of how the task can be accomplished:

document.body.innerHTML = document.body.innerHTML.replace(match, '<span class="match">' + match + '</span>');

Remember to style the .match class accordingly.

IMPORTANT: The match variable represents the keyword to be highlighted.

Answer №3

If you want to extract the complete HTML content of a webpage, you can achieve this by:

var pageHTML = document.body.innerHTML;

To replace every instance of a word with a specific markup using JavaScript, you can use the following code snippet:

"the sky is blue".replace(/sky/g,"<span class='highlight'>sky</span>");

You can then define the 'highlight' class in your CSS file for customization.

In order to narrow down your search to only text within the HTML structure, consider refining your criteria accordingly.

Answer №4

You can check out a demo on CodePen here.

$(document).ready(function(){
  $("#selector").on('keyup', function(e){
    var inputText = $.trim($(this).val());
    if(inputText !== '' && inputText !== ' '){
        var regexPattern = new RegExp(inputText, "gi");
    }
    $('p, div, span').each(function(index){
        var element = this;
        var originalText = $(element).text();
            originalText = originalText.replace(regexPattern, function($match){
            return "<span style='background:yellow'>" + $match + "</span>";
        });
        $(element).html(originalText); 
    });   
  });
});

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

Problem encountered with a form element generating additional input fields upon click of a specific button

My goal is to create a button that dynamically adds email input fields to a form titled "Add Another Email". I have a function in place to trigger this action upon clicking the button, but unfortunately, nothing happens when the button is clicked. Surprisi ...

Is there a way to export static HTML from Next.js to different directories at once?

My Next.js website is static with 1 million pages, but I am facing an issue where all the exported pages are stored in the same folder, requiring a lot of RAM to access files. Is there a way to export pages into multiple folders, maybe grouping 100k pages ...

What is the best way to group data by a specific value within a nested object when using ReactJS material-table?

I have a unique scenario where I possess an array of individuals featuring a nested object known as enterprise. My objective is to effectively group these individuals by the value of company.name within the confines of the Material-Table. const people = [ ...

appear on the screen of a Samsung smart television

Can anyone offer some assistance? I am currently working on this in JavaScript. $('#popup').sfPopup({ text: 'Would You like to close this popup?', buttons: ['Yes', 'No'], defaultFocus: 1, ...

While attempting to deploy on Vercel, I encountered an error while constructing my Next.js project

While working on my Next login signup project, I encountered the following error: WagmiProviderNotFoundError: `useConfig` must be used within `WagmiProvider`. The documentation for this issue can be found <a href="https://wagmi.sh/react/api/WagmiProvide ...

Methods for identifying when a Vue component has been updated based on property change

I have a requirement to show a spinner in every Vue component. My initial thought is to use v-if="loading" within the component's HTML. How do I know when a component has finished loading? In other words, how can I tell when the DOM has be ...

Mastering the use of expressions in ng-click and ng-show in AngularJS

I've been working on creating expandable rows within a table, but I'm encountering some issues. Despite not receiving any error messages, the functionality isn't behaving as expected. I suspect there might be an issue with how I'm using ...

The concept of React.cloneElement, higher order components, and transclusion in React

Currently, I am working on constructing a table control using React that closely adheres to this structure right down to the cells: class Table extends Component { static propTypes = { tableClass: PropTypes.string, columnDefin ...

various operations in routes using Express.js

Hey there, I am new to express js and I am looking to include multiple functions within routes. Can someone explain how to add multiple functions within a route? I have 2 functions in company.js but I am unsure how to export and add them in index.js. Here ...

Guide on looping through an array of objects and eliminating each item using JavaScript

someArray = [{name:"Ibrahim", cid:322}, {name:"Ismail", cid:423}]; Exploring this task further, I am seeking a reliable method to iterate over the array, perform certain actions, and eventually produce the desired output like so: someArray = []; This is ...

Angular and Bootstrap do not support margin styles

While working with Angular 5 and Bootstrap, I have encountered an issue with using inline styles for margin. The template I am using is as follows: @Component({ selector: "dynamic-container-component", template: ` <div styl ...

Extension for web design snippet

My program creates dynamic html documents using specific parameters, but there is one section that remains static and is pulled from a local text file. What would be the most appropriate file extension to use for this particular snippet? htm(l): Although ...

Unable to view new content as window does not scroll when content fills it up

As I work on developing a roulette system program (more to deter me from betting than to actually bet!), I've encountered an issue with the main window '#results' not scrolling when filled with results. The scroll should always follow the la ...

Fixed Navbar at the top of the page with no elements underneath

Currently, I am working on creating a sticky navbar for a school project website. You can check out the site here: I am aiming to ensure that the content does not overlap with the navbar when scrolling. I want the content to appear beneath the navbar as i ...

How can I extract the URL from the event listener in Cordova's in-app browser event and then automatically close it once a specific URL is reached?

In my journey with ionic version 1 (just starting out with ionic & angularjs), I encountered an issue while trying to close the in app browser upon reaching a specific URL. The problem arises from the fact that the event triggered on "loadstart" is o ...

Apply a unique font to the gridview that is not universally available on all systems

Can I use a custom font for my gridview that is accessible to all users, even if it doesn't exist in all systems? Is there a way to include the font in the project folder so that it can be viewed by everyone? ...

Experiencing trouble with setting values in JavaScript?

I have my code set up to display numbers 170 and 122 using Javascript, but I'm not seeing the expected output. <!DOCTYPE html> <html> <body> <button onclick="UidToPost()">Get It</button> <script> ...

The autocomplete feature in React is not displaying properly due to a problem with rendering

I am currently working on creating an autocomplete/autosuggest search bar using the Material-UI library with data fetched from an API. Below is a step-by-step breakdown of the code implementation. We first define the options for the autosuggest search bar ...

Encountering a JavaScript heap out of memory error during the upgrade from Angular v11 to v12

After running my filesystem indexing script to refresh RAID files index for 4 hours, it unexpectedly crashed with an error. View error image here The server has 8GB of RAM. During the upgrade from Angular v11 to v12, I encountered an error. Everything w ...

Troubleshooting compatibility issues between jQuery scrollLeft and Angular

As I attempt to programmatically scroll a horizontally overflowing div, I am confident that my final code should resemble the following: var $element = $('#widgetRow');//or maybe $('#widgetRow').parent(); //With 1 or more parent()& ...