-2

I have made a small program that search value from a div...it show first location of the word But i want to make that searched word highligheted after pressing search button at all repeated location..

<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 tried so many times but couldnot get an idea to make highlight a specific text in div by javascript...???? If anybody have please tell me

4 Answers4

2
<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);
    var anshu=str.substring(n,(n+keyword.length)); 
    //alert('Word Found :'+anshu);

    var af = document.getElementById("area");
    af.innerHTML = str.slice(0, n) 
    af.innerHTML += '<b>' + anshu + '</b>';
    af.innerHTML += str.slice(n+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="search()"/>
     <br>
     <div style="width:444px;" id="area" name="textarea">rajendra kumar rahar from jhunjhunu</div>
</div>
</body>
<html>
anshuVersatile
  • 398
  • 2
  • 13
1
new_html = "<div class='highlighted'>" + n + "</div>";
anshuVersatile
  • 398
  • 2
  • 13
1

You could slice the innerHTML, add a tag, and concat it back. So, at the end of search put:

var a = document.getElementById("area");
a.innerHTML = str.slice(0, n) 
a.innerHTML += '<b>' + keyword + '</b>';
a.innerHTML += str.slice(n+keyword.length);

I don't see any easy way allow the dehighlighting of text, though.

Gavin Haynes
  • 1,721
  • 11
  • 21
0

try something like this

var high = "<div class='highlighted'>"+n+"</div>";
document.getElementById("area").innerHTML = str.replace(n,high); 
rajesh kakawat
  • 10,826
  • 1
  • 21
  • 40