naik3
naik3

Reputation: 309

Highlighting a word or sentence in iframe, using javascript/Jquery

I am trying to change the background colour of word in iframe tag. I am able to search the word, but not getting how to change the colour. Here is my code.

$(document).ready(function () {
   $('#content').contents().find('head').append($("<style type='text/css'> .red{color:red;}</style>"));
   var cont = document.getElementById('content').contentWindow.document.body.innerHTML;
          
   if($("#content").contents().text().search("SEARCH WORD")!=-1){
     console.log("Found");
     //<span class="red"> SEARCH WORD </span>
   }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="padding-left: 0px;" class="col-sm-8 text-center">
  <iframe id="content" ng-src="http://locahost:8888/public/textfiles/sample.txt" 
          width="100%" height="500px" align="middle"></iframe>&emsp;
</div>

Upvotes: 1

Views: 2937

Answers (2)

Andrew L
Andrew L

Reputation: 5496

As noted, CORS will not allow you to alter iFrames sourced from other domains you do not control without the proper CORS heading.

If you are on the same domain, you can possibly do something like find the word, alter it, and then replace the contents of the iframe with your new code. Here is a working fiddle and code For example:

<iframe src="http://fiddle.jshell.net/_display/" id="myIframe"></iframe>
<script>
var searchWord = "error";
$(document).ready(function(){
    $('#myIframe').ready(function(){
        var $html = $($('#myIframe').contents().find('body').html());
     if($html.contents().text().search(searchWord)!=-1){
       console.log("Found");
       var replaceWith = "<span style='color:red'>"+searchWord+"</span>"
       var newHTML = $html.text().replace(searchWord, replaceWith);
       $('#myIframe').contents().find('body').html(newHTML);
     }
   });
});
</script>

Upvotes: 1

Cosmin_Victor
Cosmin_Victor

Reputation: 154

Please don't forget the cross-domain policy, otherwise it won't work. And check this Search for word and highlight with jquery

Upvotes: 0

Related Questions