The jQuery find and replace feature is causing my entire content to be replaced instead of just specific paragraphs

Within this section, there are multiple paragraphs and an input field. The concept is simple: the user inputs text into the box, then hits "ENTER" to trigger a jquery function below.

The process involves identifying matches between the paragraph content and the user input. When a match is found, the paragraph's HTML is essentially updated with a span element wrapping the matching text. This allows for easy CSS styling to highlight the matched text.

However, a current issue I'm facing is that when the text is replaced, it affects all instances of that specific HTML element type on the entire page. It may be challenging to explain in words, so feel free to explore the behavior using this provided fiddle. Enter easily identifiable text and observe the outcome.

Is there a way to regenerate the text element by element instead of duplicating every instance?

<input type="text" id="searchbox">
<p>Let's get some text to test</p>
<p>This is another paragraph</p>

function searchHighlight(searchText){
    if(searchText){
        // Variable declaration for question content
        var content = $('p').text();

        // Variable declaration for search phrase
        var searchExp = new RegExp(searchText, "ig");

        // Variable declaration for match identification
        var matches = content.match(searchExp);

        // If text is found within the QUESTION, proceed as follows...
        if(matches){
            $("p").html(content.replace(searchExp, function(match){
                return "<span class='selected'>" + match + "</span>";
        }))
    }
    else{
        $("#searchbox").css("border", "1px solid red")
    }
}

Access the demo through this link: https://jsfiddle.net/awv5r1f0/1/

Answer №1

To get the desired outcome, use the following approach with the 'each' method to search for a specific word and replace it in the p html tag.

Problem: Using $("p").html() will update all p tags and replace them with the same text.

  1. Update by iterating through all the p elements
  2. Use $(this).html to update only the p element containing the matching word
$("p").each(function() {
    $(this).html($(this).text().replace(searchExp, function(match) {
        return "<span class='selected'>" + match + "</span>";
    }))
})

Sample code

$(function() {
    // Add event listener for pressing enter key in the searchbox
    $("#searchbox").on("keydown", function(event) {
        if (event.which == 13) {
            // Call the searchHighlight function
            searchHighlight($(this).val())
        }
    })
})

function searchHighlight(searchText) {
    if (searchText) {
        var content = $('p').text();
        var searchExp = new RegExp(searchText, "ig");
        var matches = content.match(searchExp);
        
        if (matches) {
            $("p").each(function() {
                $(this).html($(this).text().replace(searchExp, function(match) {
                    return "<span class='selected'>" + match + "</span>";
                }))
            })
        } else {
            $("#searchbox").css("border", "1px solid red")
        }
    }
}
.selected{
  background: yellow;
  font-weight: 700;
}
#searchbox{
  border: 1px solid #ccc;
  outline: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="searchbox">
<p>Let's get some text to test</p>
<p>This is another paragraph</p>

Answer №2

Although it may not be the perfect solution, I believe it meets your requirements. The issue was that you were altering the html of every p element you had, not just the one where the word was matched.

To address this, I utilized an each method to scan all the p elements and insert a span where the match occurred. This approach would function effectively even if there are multiple paragraphs (p) containing the match.

Refer below for the implementation:

$(function() {
  // Create event for enter key in searchbox
  $("#searchbox").on("keydown", function(event) {
    if (event.which == 13) {
      // execute searchHighlight function
      searchHighlight($(this).val())
    }
  })
})

function searchHighlight(searchText) {
  if (searchText) {
    // Declare variable content to store question content
    var content = $('p').text();

    // Define searchExp variable for search phrase
    var searchExp = new RegExp(searchText, "ig");

    // Variable to hold found matches
    var matches = content.match(searchExp);

    // Perform actions when text is found in QUESTION
    $('p').each(function() {
      if ($(this).text().match(searchExp)) {
        $(this).html($(this).html().replace(searchExp, function(match) {
          return "<span class='selected'>" + match + "</span>";
        }))
      } else {
        $("#searchbox").css("border", "1px solid red")
      }
    })
  }
}
.selected {
  background: yellow;
  font-weight: 700;
}

#searchbox {
  border: 1px solid #ccc;
  outline: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="searchbox">
<p>Let's get some text to test</p>
<p>This is another paragraph</p>

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

I need clarification on some basic concepts about ajax - Can you help?

Could someone please assist me in clarifying a concept? Currently, I am utilizing the colorbox plugin to load an external html snippet (which is functioning correctly). However, my jquery selectors are unable to detect the newly loaded html. Is this the co ...

Building HTML tables with JQuery for handling large datasets of over 4,000 rows and beyond

My goal is to create a table with 4000+ rows and 18 columns displaying parsed pages from my site. I need it all on one page for the following reasons: I require the use of filters in the table I need to be able to sort by more than 5 columns Every cell ...

Having issues with Node.js POST requests not functioning properly

Currently diving into learning the MEAN stack and facing a challenge with executing POST requests on the server. Here is a snippet from my server.js script: var express = require('express'); var bodyParser = require('body-parser'); v ...

Tips for creating a fixed element with ScrollTrigger and GSAP

How can I prevent the right div from jumping on top of the left div when using a scroll trigger to make the left div's position fixed? gsap.registerPlugin(ScrollTrigger); const tlfour = gsap.timeline({ scrollTrigger: { trigger: ".ma ...

How can HTML and CSS be linked to display images independently?

Check out this code: body{ background-image:url('http://wallpoper.com/images/00/31/33/51/black-background_00313351.jpg'); } div.header{ background-color:#F0F8FF; text-align:center; padding:3px; ...

Checking to see if the prop 'isChecked' has been modified

I'm currently facing a challenge with testing whether a class's prop value changes after clicking the switcher. Below is the component class I am working with: import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core&a ...

Refreshing a Next.js page results in a 404 error

I've set up a Next.js page called page.js that can be accessed through the URL http://localhost:3000/page. However, I have a need to access this page through a different URL, namely http://localhost:3000/my-page. To achieve this, I decided to utilize ...

The Req.session array is limited to storing just one element at a time

I'm currently working on integrating a shopping cart feature into my Express/MongoDB e-commerce app that sells sneakers. To add an item to the cart, I extract the quantity and size from req.body and the itemId from req.session (previously saved when l ...

Issue with vue-template-compiler in Vue.js 3 webpack configuration

I am currently working on integrating vuejs 3 into a project that already utilizes webpack. I have been looking into using vue-loader as part of this process. After consulting the official documentation, I came across the following information: Every new ...

leveraging a callback function alongside the useState hook

I'm facing an issue with the change() function. My goal is to call the filteredData() function after the setState operation is completed. Typically, I would use a callback function for this task, but useState doesn't support callbacks. Using useE ...

How can I adjust a centered container div to fit properly on a mobile device

Exploring the centering of a particular div: #container { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); height: 550px; width: auto; background: rgba(28, 28, 54, 0.70); padding: 15px; border: 1px solid #1c ...

Clicking on a jQuery element will reveal a list of corresponding elements

I've retrieved a list of elements from the database and displayed them in a table with a button: <a href="#" class="hiden"></a> To show and hide advanced information contained within: <div class="object></div> Here is my jQ ...

jQuery AJAX call with datePicker function is functional on all browsers except for Internet Explorer versions 6 and 7

Struggling with the issue of why this specific jQuery code is failing to work in IE 6 or 7: $("#date").datepicker({ dateFormat: "mm-dd-yy", altFormat: "yy-mm-dd", altField: "#realdate", onSelect: function(dateText, inst) { ...

How to show a picture stored in a MySQL database using PHP

I have been experimenting with displaying images uploaded to the database using a simple insert form. So far, I have managed to retrieve the image name in the "data-file". However, I am curious about how I can easily display the actual image in the same lo ...

Creating Dynamic Web Design: Horizontal Scrolling Window and Adaptive HTML Content

After spending countless hours researching online, I am still unable to find a solution for responsive web design that maintains the aspect ratio of both the window and HTML body. Here are examples of what I'm looking for: original view, stretched le ...

Tips for submitting by simply choosing an option from a dropdown using jQuery?

Upon selecting a different week (uke) from the dropdown on the right or a trainer from the left dropdown above the schedule, it will automatically submit. There's no need to manually click the Submit(Vis) button. Is there a way to submit when just se ...

I am attempting to implement a feature that changes the color of buttons when they are clicked within an ng-repeat loop

A problem is occurring with the ng-class directive in this HTML code, which is generating seats using the ng-repeat directive. The colors are not being added properly when a seat is selected. If you'd like to view my code, it can be found in this JSf ...

The issue with IE rendering shadows and how it relates to jQuery

Recently, I attempted to use jQuery to create a "fade in" effect on a section of my website. However, when testing it in IE8, I encountered an unexpected issue. While the box successfully faded in, the shadow that appeared during the transition displayed a ...

Troubleshooting: Issue with v-link to classname in Vue.js

This is the code I am working with: <div v-link="'/work/' + {{data.useClass}}" class="itemImg {{data.useClass}}"> When rendered in the browser, it looks like this: <div class="itemImg x50"> The expectation is that class="itemImg { ...

Ordering tables in jQuery with both ascending and descending options

Trying to sort a table in ascending and descending order using jQuery? Here's the JavaScript code for it. However, encountering an error: Cannot read property 'localeCompare' of undefined If you can provide guidance on how to fix this so ...