Activate real-time highlighting by clicking on the search button

I created a simple program that searches for a value within a div and displays the first location of the word. However, I am looking to enhance it by highlighting all repeated locations of the searched word after pressing the search button.

<html>
<head>

<style type="text/css">
#searchdiv{background-color: #999999;left: 277px;margin: 39px 0 0 84px;padding:5px;width:500px;align:center;}
</style>
<script type="text/javascript">
function search()
{
    var keyword=document.getElementById("keyword").value;
    var str=document.getElementById("area").innerHTML;
    var n=str.search(keyword);
    alert('Location is :'+n);
}
</script>
<body>
<div id="searchdiv">
     <input type="text" id="keyword" name="text" size="70" />
     <input type="button" value="search" id="btn" name="button" onclick="search()"/>
     <br>
     <div style="width:444px;" id="area" name="textarea">rajendra kumar rahar from jhunjhunu</div>
</div>
</body>
<html>

I have attempted multiple times but haven't been able to figure out how to highlight specific text within a div using JavaScript... Can anyone provide assistance? If you have any solution, please share with me

Answer №1

<html>
<head>

<style type="text/css>
#searchdiv{background-color: #999999;left: 277px;margin: 39px 0 0 84px;padding:5px;width:500px;align:center;}
</style>
<script type="text/javascript>
function searchFunction()
{
    var keyword=document.getElementById("keyword").value;
    var text=document.getElementById("area").innerHTML;
    var index=text.search(keyword);
    var foundText=text.substring(index,(index+keyword.length)); 
    
    var result = document.getElementById("area");
    result.innerHTML = text.slice(0, index) 
    result.innerHTML += '<b>' + foundText + '</b>';
    result.innerHTML += text.slice(index+keyword.length);
}
</script>
<body>
<div id="searchdiv">
     <input type="text" id="keyword" name="text" size="70" />
     <input type="button" value="search" id="btn" name="button" onclick="searchFunction()"/>
     <br>
     <div style="width:444px;" id="area" name="textarea">rajendra kumar rahar from jhunjhunu</div>
</div>
</body>
<html>

Answer №2

highlighted_div = "<div class='featured'>" + n + "</div>";

Answer №3

If you want to highlight a keyword within the innerHTML of an element, one approach is to slice the string, insert the desired tag around the keyword, and then concatenate the parts back together. For example, after performing a search, you can include the following code:

var element = document.getElementById("targetElement");
var str = element.innerHTML;
element.innerHTML = str.slice(0, index) + '<b>' + keyword + '</b>' + str.slice(index + keyword.length);

Unfortunately, there isn't a straightforward way to remove the highlighting once it has been applied.

Answer №4

consider giving this a shot

var highlight = "<span class='highlighted'>" + n + "</span>";
document.querySelector("#area").innerHTML = str.replace(n, highlight);

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

Step-by-step guide on sorting WordPress posts by a custom field date

I've created an event sidebar section that will only show the next 3 upcoming events. I have successfully set up the custom post type and custom fields, but I am struggling to figure out how to order the posts based on the start date of the events, wh ...

Unable to get CSS transition to function properly after adding a class using jQuery

I am trying to create a hover effect that shows an image when the mouse is over a specific div, but for some reason, the transition is not working as expected. I understand that using visibility: hidden cannot be animated. Here is the code snippet: $(d ...

Utilize jQuery to extract all values from the second cell of a table and store them in an array

I have a task that involves pushing numbers from text boxes into an array. These text boxes are located in the second cell of each table row, while the third cell contains a date picker. Currently, the code snippet provided retrieves all values from both ...

Automatically collapse the responsive menu upon selecting a menu item

I have implemented a custom JavaScript code for a basic open/close menu movement on multi-page websites. The code works by closing the menu only when the user clicks the menu symbol. However, I now need to incorporate this code into a one-page website and ...

Incorporating a splash of color while changing the background color on scroll

Is it possible to include more colors between the "beginning-color" and the "ending-color" in this code that changes the background color on scroll? example $(document).ready(function(){ var scroll_pos = 0; var animation_begin_pos = 0; ...

Leveraging React Native to retrieve information from a promise in JSON format

After successfully fetching the JSON data, I now have an array. My question is how can I utilize the elements within this array in a React Native environment? Below is my current approach: export default function display() { const fetching = async() => ...

When the Materialparameters property transparent is set to true in threejs, the object becomes invisible

Currently, I am enrolled in Bruno Simons' class and in the session "Haunted House," he is teaching how to incorporate textures. So far, everything seems to be running smoothly and all the map textures are functioning perfectly. However, when I input t ...

Jersey: JSON Media Type Not Supported

I am looking to develop a REST API that can retrieve JSON data and send JSON data as well. Here is an example of my Book class : @Entity public class Book { @Id private String isbn; public Book() { } ...... } And this is my Boo ...

`Shuffle the order of Vue.js elements upon page load for a randomized effect`

I need help targeting specific elements using the ref attribute in Vuejs to randomize their order every time the page loads. The data is displayed in the template and managed in the component: <div class="team" > <div class="team__card" ref="c ...

Struggling to accurately convert the string into a date object

I have an array of objects structured like this: const days = [ { _id: 12312323, date : '30/12/2021', dateStatus : 'presence' }, ... ] I am looking to convert the date property from a string to a Date object using the follo ...

Transitioning jQuery .load and the usage of sorttable.js for sorting data

My jQuery code snippet is as follows: $("#loadBtn").click(function(){ $('#div1').delay(200).slideUp('slow') .load ('page2.php #div2').hide().delay(300).slideDown('slow'); return false; ...

Setting the default selection in a closed dropdown menu with ng-Options

In my Angular project, I have a select dropdown that is populated from an array. Each entry in the array is in lowercase format. The variable "selected" that I use in other parts of my code needs to be in lowercase. However, the entries displayed in the ...

Article with content surpassing the boundary of its parent container

I'm struggling to contain text within the parent's div as it keeps overflowing. I attempted using element.style { text-overflow: ellipsis; overflow: hidden; } but unfortunately, it didn't work. Take a look here at my JSFiddle link. It ...

Do not deserialize the list of child objects in Jackson

Upon receiving the JSON, the data is as follows: {"firstName":"charle","lastName":"charly","books":[{"title":"navle"}]} I then attempt to convert it into a Jackson object like so: @JsonIgnoreProperties(ignoreUnknown = true) public class Person { @Id ...

java code unicode feature in csharp

Here's the code I am using: $(document).ready(function () { var breadCrumps = $('.breadcrumb'); breadCrumps.find('span').text("<%= ArticleSectionData.title %>"); }); The 'title' property contains values en ...

Using a Java regular expression to search within a text file

Is there a way to use regular expressions to search and replace strings in multiple files? I have a group of files and need to find a specific string and replace it in all files. Could someone provide assistance with the following code: package com.java. ...

Trouble with Dropdown functionality in Laravel after switching pages

Having an issue here: when the page loads, I have a dropdown menu for language selection which works perfectly fine. However, when I navigate to another page on the site (only works on viewport width less than 1920px), it should appear upon clicking in th ...

jQuery validate not enforcing minimum value constraints as expected

I've come across an issue with my validation code. It seems to work properly when I enter text in a number field. However, when I input a value below 1 (which is the minimum set in the rules), no error message appears as expected. jQuery(function() { ...

The image I want to show is invisible on the CSS custom radio button

I'm having trouble creating a custom radio button that displays the image I want. The current setup doesn't seem to be working as expected. label { font-weight: lighter; cursor:pointer; } input[type="radio"] { display:none; } in ...

Combining Bootstrap Grids

Is there a way to seamlessly merge two grids as one larger grid without altering the current HTML structure? Currently, it displays as: Child[0] Child[1] Child[2] Child[3] I would like it to display as: Child[0] Child[1] Child[2] Child[3] <div id=& ...