Tips for utilizing javascript to reset the heightline of the preceding keyword during a keyword search

Using JavaScript, I have implemented a search keyword function that highlights specific words in a paragraph. However, I am facing an issue. Currently, when searching for the next keyword, the previously highlighted text remains in red instead of reverting back to the original black color. How can I modify this code to ensure that the previous search keyword is not highlighted in red when searching for a new keyword? Any suggestions on optimizing this solution would be greatly appreciated. Thank you in advance for your assistance.

let search = document.querySelector('#js-search');
let content = document.querySelector('p');
let key = document.querySelector('#keyWord').value;


function highlight(content, key){
  return content.replace(new RegExp(key,'gi'),(match)=>{
    return `<span style="color:red">${match}</span>`;
  });
}


search.addEventListener('click',() =>{

  const  keyword = $('#keyWord').val();
  const matchs = $("p:contains("+ keyword +")");
  matchs.each(function(){
    const content = $(this).html();
    $(this).html(highlight(content,keyword));
  });
});
.red{
  color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="keyWord" type="text"><button id="js-search">search</button>

<ul>
  <li>
    <h1>eturn problem</h1>
    <p>I am an example of related content</p>
  </li>
  <li>
    <h1>credit card problem</h1>
    <p>This is about credit card issues, you can search for keywords to find keywords</p>
  </li>
  <li>
    <h1>order cancellation problem</h1>
    <p>order cancellation problemThis is a sample text of random typing content</p>
  </li>
</ul>

Answer №1

Make sure to save the original HTML content and then restore it whenever the search button is pressed.

let search = document.querySelector('#js-search');
let content = document.querySelector('p');
let key = document.querySelector('#keyWord').value;
let html = document.querySelector('.container').innerHTML;

function resetHighlight() {
  document.querySelector('.container').innerHTML = html;
}

function highlight(content, key){
  return content.replace(new RegExp(key,'gi'),(match)=>{
    return `<span style="color:red">${match}</span>`;
  });
}


search.addEventListener('click',() =>{
  resetHighlight();
  const  keyword = $('#keyWord').val();
  const matchs = $("p:contains("+ keyword +")");
  matchs.each(function(){
    const content = $(this).html();
    $(this).html(highlight(content,keyword));
  });
});
.red{
  color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="keyWord" type="text"><button id="js-search">search</button>

<ul class="container">
  <li>
    <h1>eturn problem</h1>
    <p>I am an example of related content</p>
  </li>
  <li>
    <h1>credit card problem</h1>
    <p>This is about credit card issues, you can search for keywords to find keywords</p>
  </li>
  <li>
    <h1>order cancellation problem</h1>
    <p>order cancellation problemThis is a sample text of random typing content</p>
  </li>
</ul>

Answer №2

You have the option to choose highlighted components and eliminate the highlighting on each one.

Here, I have revamped the code to utilize classes rather than style attributes for simplification.

Subsequently, I utilize element.replaceWith to substitute the span with a standard text node.

let search = document.querySelector('#js-search');
let content = document.querySelector('p');
let key = document.querySelector('#keyWord').value;

function resetHighlight() {
  const highlightedElements = document.querySelectorAll('.highlighted')
  for (let element of highlightedElements) {
    const textNode = new Text(element.textContent);
    element.replaceWith(textNode)
  }
}

function highlight(content, key){
  return content.replace(new RegExp(key,'gi'),(match)=>{
    return `<span class="highlighted">${match}</span>`;
  });
}


search.addEventListener('click',() =>{
  resetHighlight();
  const  keyword = $('#keyWord').val();
  const matchs = $("p:contains("+ keyword +")");
  matchs.each(function(){
    const content = $(this).html();
    $(this).html(highlight(content,keyword));
  });
});
.highlighted{
  color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="keyWord" type="text"><button id="js-search">search</button>

<ul>
  <li>
    <h1>eturn problem</h1>
    <p>I am an example of related content</p>
  </li>
  <li>
    <h1>credit card problem</h1>
    <p>This is about credit card issues, you can search for keywords to find keywords</p>
  </li>
  <li>
    <h1>order cancellation problem</h1>
    <p>order cancellation problemThis is a sample text of random typing content</p>
  </li>
</ul>

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

Update array when checkbox is selected/deselected

Using angular-google-maps, I am creating a map with various types of markers. Below the map, there are checkboxes in a simple form: <div class="mapOptions"> <form action="" class="form-inline" style="text-align:center"> <label for=""& ...

Having trouble getting the Bootstrap modal form to submit when using Knockout's submit binding?

Check out my jsFiddle example by clicking here. I am currently working on a form within a bootstrap modal. The problem I'm facing is that the knockout submit binding doesn't get executed unless the user clicks on the submit input. It seems like ...

What is the difference between TypeScript's import/as and import/require syntax?

In my coding project involving TypeScript and Express/Node.js, I've come across different import syntax options. The TypeScript Handbook suggests using import express = require('express');, while the typescript.d.ts file shows import * as ex ...

When attempting to toggle the view on button click, it is not possible to select a shadowRoot

I am facing an issue with my parent component named ha-config-user-picker.js and its child component called edit-user-view.js. Parent Component: It contains a mapping of users and includes the child component tag along with its props. When a click event i ...

Does anyone know of a CSS/JavaScript framework that can be used to replicate the look and functionality of the iOS home

I'm wondering if there is a CSS/JavaScript framework that replicates the layout of an iOS home screen. I want to create a kiosk website with a grid layout similar to Android/iOS where apps can be displayed as icons. ...

Is it possible for a memory leak to occur in node.js when using new Date()?

For this particular case, when updating an existing MongoDB document with new Date() causing a potential memory leak is a question that arises. One might wonder if allocating a new object with the new keyword necessitates manual deallocation to prevent lea ...

Searching for a different method in JavaScript that can add items without duplication, as the prependTo function tends to insert multiple items

Every time my code runs successfully, a success message is generated and displayed using prependTo within the HTML. However, the issue arises when the user performs the successful action twice, resulting in two success messages being shown on the screen. ...

The issue with jspdf is that it is failing to generate PDF documents of

I'm currently developing a resume builder app using ReactJS. One of the functionalities I'm working on is enabling users to download their resumes as PDFs. However, I've encountered an issue with the generated PDFs when using jsPDF. The down ...

React is unable to properly utilize Mui icons in a basic Card example

C:\Users\Yeap\Documents\react sitio web\my-app\node_modules\react-scripts\scripts\start.js:19 throw err; ^ [Error: ENOENT: no such file or directory, stat 'C:\Users\All Users'] { errno ...

Issue with Angular not rendering data retrieved from HTTP response

In my Service script class, I have defined a HomeApiService with the following code: export class HomeApiService{ apiURL = 'http://localhost:8080/api'; constructor(private http: HttpClient) {} getProfileData():Observable<HomeModelInterface[ ...

Tags that adhere to W3C compliance for struts

I'm facing an issue with a web page created using struts tag libraries. When attempting to validate the page on w3c.org, all the struts tags are showing up as undefined. For example, <html:button> appears as undefined. The DOCTYPE I used is: &l ...

What is the best way to incorporate an image zoom-in effect into a flexible-sized block?

Having a fluid grid with 3 blocks in one row, each set to width:33.3%. The images within these blocks are set to width: 100% and height: auto. I am looking to implement a zoom-in effect on hover for these images without changing the height of the blocks. I ...

How to showcase an image with Angular 2?

Just starting out with Angular 2 and ran into an issue while trying to display an image using a relative path. <img src="./../images/publicVideo1.PNG"> Unfortunately, I encountered the following error: null:1 GET http://localhost:4200/null 404 (No ...

Exploring the Modularity of Post Requests with Node.js, Express 4.0, and Mongoose

Currently, I am immersed in a project that involves utilizing the mean stack. As part of the setup process for the client-side, I am rigorously testing my routes using Postman. My objective is to execute a post request to retrieve a specific user and anot ...

Forecasting text input demands

Many websites display suggestions in a drop-down menu as you type, some even showing a preview of the most likely result in a lighter-gradient font next to the cursor. For example, Spotlight on my Mac does this: https://i.sstatic.net/hDyxG.png Spotlight ...

Is there a way to showcase Ajax data in an alert window and simultaneously integrate dynamically added data?

I am using a PHP script to fetch data in the following way: $.ajax({ url: './fetchData.php', type: "POST", data: { mail: mail }, dataType:'text', success: function(ans) { var data = JSON.parse(ans); $(' ...

I am interested in developing a Menu system that features different categories and subcategories

I am in need of assistance in creating a menu that includes both categories and sub categories. An example of what I am looking to achieve can be seen on the website www.boots.com If anyone has any suggestions or advice to offer, I would greatly apprecia ...

Sending a personalized event to a JavaScript object

I am looking to create an object Constructor that can dispatch a customEvent, which I then want to listen to from the instance of the object. The code snippet provided showcases what I have been attempting. I would appreciate any assistance on how to mak ...

Conceal objects in reverse sequence

My goal is to clear notifications grouped on a mobile OS style interface when clicking the "X" button. They should be removed in reverse order with a 1-second delay between each. Here's what I've achieved so far: $(document).ready(function () { ...

Currency unique to a specific culture

Recently, I encountered an issue while working on a website that involved using JavaScript code to format currency values. Here is the snippet of code that was causing the problem: UsdAmount.toLocaleString(siteCulture, {style: 'currency', ...