Tips for emphasizing specific text within HTML tags without highlighting the tags in Vue

I am using a tag with v-html to render HTML text and display it, like so:

<div v-html="htmlText"></div>
I have written code to highlight text and it works on regular text:

Vue.filter('highlight', function (word, query) {
  if (query !== '') {
    let check = new RegExp(query, "ig");
    return word.toString().replace(check, function (matchedText, a, b) {
      return ('<strong class="mark">' + matchedText + '</strong>');
    });
  } else {
    return word;
}
<div v-html="$options.filters.highlight(htmlText, myWord)">
</div>

I am trying to highlight a specific word within this text without affecting the HTML tags. Can someone please assist? Thank you.

Answer №1

If you're open to using external libraries, one option is mark.js.

With mark.js, you can easily highlight text using regular expressions and apply it across HTML elements. Below is a Vue example demonstrating how mark.js can be integrated:

var demo = new Vue({
  el: '#demo',
  data: {
    // The html content to be highlighted
    html: '<div>Hello <span>this </span>is <span>some </span>text</div>',
    
    // The html content with highlighting applied
    highlightedHtml: '',
    
    // The search term for highlighting
    search: 'Hello'
  },
  watch: {
    // When the search term changes: recompute the marked html content
    'search': {
      handler: function() {
        // Create an element with the given html content and assign a unique id 
        // for potential removal in the future
        let id =  'id' + (new Date()).getTime();
        $('body').append(`<div id="${id}" style="display:none">${this.html}</div>`);
        
        // Instantiate a Mark instance on the newly created element
        let markInstance = new Mark('#' + id);
        
        // Mark the text with the specified search string. Upon completion,
        // update the highlighted text and remove the temporary element
        markInstance.markRegExp(new RegExp(this.search, 'gmi'), {
          done: () => {
            this.highlightedHtml = $('#' + id)[0].innerHTML;
            $('#' + id).remove();
          },
          acrossElements: true,
        });
    },
      immediate: true
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.0/mark.js"></script>

<div id="demo">
  <div>/ <input type="text" v-model="search"> /gmi</div>
  <div v-html="highlightedHtml"></div>
</div>

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

Retrieving JSON data in Angular 2

There are limited options available on SO, but it seems they are no longer viable. Angular 2 is constantly evolving... I am attempting to retrieve data from a JSON file in my project. The JSON file is named items.json. I am pondering if I can achieve th ...

Update the designated dropdown menu using its identification number

I have discovered a way to change the selected dropdown item by value, but I am interested in doing it by the option ID instead. The reason for this is that the values are dynamically generated. Currently, I am working on creating a questionnaire that incl ...

Struggling to use the innerHTML method to update a div within another div element?

<!DOCTYPE html> <html> <head> <title>Business Information Card</title> <script type="text/javascript"> window.onload = init; function init(){ var button = document.getElementById("populate ...

"Clicking on a jQuery div will cause it to slide down, and clicking again

I am currently working on this code snippet: $("#right").click(function() { $("#signin").stop().slideDown(300); }); At the moment, it drops down when clicked, but I would like it to slideUp() when clicked again. Your help is appreciated. On a relate ...

Importing Global Sass Styles in Nuxt 3 for Static Assets

I'm currently attempting to import a global Sass stylesheet from the /assets directory in order to utilize variables and mixins defined there throughout the components. My current configuration in nuxt.config.ts is as follows: import { defineNuxtConfi ...

When decoding a JWT, it may return the value of "[object Object]"

Having some trouble decoding a JSON web token that's being sent to my REST API server. I can't seem to access the _id property within the web token. Below is the code I'm currently using: jwt.verify(token, process.env.TOKEN_SECRET, { comp ...

Utilizing the power of Scoped CSS with Bootstrap/Bootstrap-Vue Integration

I'm currently working on a chrome extension and utilizing Bootstrap-Vue in my Vue files. I have imported bootstrap/bootstrap-vue into my js file, but the styling is being applied globally. Is there a way to scope the Bootstrap only onto specific inser ...

Error: The page "..." contains an invalid "default" export. The type "..." is not recognized in Next.js

Currently, I have a functional component set up for the Signup page. My goal is to define props within this component so that I can pass the necessary values to it from another component. This is my current approach: export default function SignupPage({mod ...

A windows application developed using either Javascript or Typescript

Can you provide some suggestions for developing Windows applications using Javascript, Typescript, and Node.js? ...

Using Express middleware in a TypeScript Express application

I'm currently converting the backend of an ExpressJS application to Typescript. While working on the auth.routes.ts file, I encountered an issue with the middleware (authMiddleware). It seems like there might be a typing error, as the same code in the ...

Determining whether a path is absolute or relative: A step-by-step guide

Is there a universal function in node.js that can determine if a given path is absolute or relative? Unlike Windows, which starts with 'C:' or '\', UNIX paths begin with '/'. ...

Incorporate a line break into a document using JavaScript

Is there a way to make all the items inside document.get on new lines without using paragraph elements? I have tried br/ and \n, but they do not work as expected. They either cause issues with JavaScript execution or fail to create new lines. <scr ...

Using BeautifulSoup to extract data from a webpage containing JavaScript

Hello everyone! I am reaching out for help once more. While I am comfortable scraping simple websites with tags, I recently came across a more complex website that includes JavaScript. Specifically, I am looking to extract all the estimates located at the ...

Having numerous bxsliders implemented in a Genesis child theme

I'm currently working on incorporating multiple bxsliders through custom fields in a wp genesis child theme. The initial slider was successfully implemented using the following function within the genesis child theme functions: add_action('genes ...

Make sure to use jQuery waterfall 'reflow' only once all the images have finished loading

Currently, I am utilizing jQuery waterfall to achieve a grid-style display on my website. To address the issue of images overlapping, I have enclosed the waterfall method within a .load() function like this: $(window).load(function(){ $('#buildcon ...

Issues with rendering child components in Vue 2 were detected

I'm currently struggling to grasp this issue. The main parent component is not displaying the child components as expected, and no errors are appearing upon page load. Here is the current code snippet: HTML: <td class="countries-visible-filt ...

What is the best approach to dynamically implement useReducer in code?

Take a look at the repository here: https://github.com/charles7771/ugly-code In the 'Options' component, I am facing an issue where I am hardcoding different names for each reducer case instead of dynamically generating them for a form. This app ...

Enhancing productivity with tools for developers and effortless tab navigation

During my development process, I always keep the developer tools open on one or more of my tabs. However, I noticed that when I switch to a tab where the developer tools were not previously open, a resize event is triggered. Strangely, this event causes el ...

Mongoose Exception: Question does not have a constructor

After coming across numerous questions on stack overflow related to this error without finding a solution that works for me, I've decided to ask my own question. (probably due to my limited understanding of javascript/node/mongoose) The modules I am ...

How to send data to res.render in Node.js?

I'm new to working with node.js. In my index.ejs file, I have included a header.ejs file. Everything seems to be functioning properly except for the fact that I am unable to pass values to the variable status in the header.ejs. index.ejs <html& ...