How to highlight text using javascript

后端 未结 13 2522
名媛妹妹
名媛妹妹 2020-11-22 02:32

Can someone help me with a javascript function that can highlight text on a web page. And the requirement is to - highlight only once, not like highlight all occurrences of

13条回答
  •  野的像风
    2020-11-22 02:55

    You can use the jquery highlight effect.

    But if you are interested in raw javascript code, take a look at what I got Simply copy paste into an HTML, open the file and click "highlight" - this should highlight the word "fox". Performance wise I think this would do for small text and a single repetition (like you specified)

    function highlight(text) {
      var inputText = document.getElementById("inputText");
      var innerHTML = inputText.innerHTML;
      var index = innerHTML.indexOf(text);
      if (index >= 0) { 
       innerHTML = innerHTML.substring(0,index) + "" + innerHTML.substring(index,index+text.length) + "" + innerHTML.substring(index + text.length);
       inputText.innerHTML = innerHTML;
      }
    }
    .highlight {
      background-color: yellow;
    }
    
    
    
    The fox went over the fence

    Edits:

    Using replace

    I see this answer gained some popularity, I thought I might add on it. You can also easily use replace

    "the fox jumped over the fence".replace(/fox/,"fox");

    Or for multiple occurrences (not relevant for the question, but was asked in comments) you simply add global on the replace regular expression.

    "the fox jumped over the other fox".replace(/fox/g,"fox");

    Hope this helps to the intrigued commenters.

    Replacing the HTML to the entire web-page

    to replace the HTML for an entire web-page, you should refer to innerHTML of the document's body.

    document.body.innerHTML

提交回复
热议问题