Highlight a word with jQuery

后端 未结 12 1364
粉色の甜心
粉色の甜心 2020-11-22 01:20

I basically need to highlight a particular word in a block of text. For example, pretend I wanted to highlight the word "dolor" in this text:



        
12条回答
  •  你的背包
    2020-11-22 01:58

    You can use the following function to highlight any word in your text.

    function color_word(text_id, word, color) {
        words = $('#' + text_id).text().split(' ');
        words = words.map(function(item) { return item == word ? "" + word + '' : item });
        new_words = words.join(' ');
        $('#' + text_id).html(new_words);
        }
    

    Simply target the element that contains the text, choosing the word to colorize and the color of choice.

    Here is an example:

    This is some text to show that it is possible to color a specific word inside a body of text. The idea is to convert the text into an array using the split function, then iterate over each word until the word of interest is identified. Once found, the word of interest can be colored by replacing that element with a span around the word. Finally, replacing the text with jQuery's html() function will produce the desired result.

    Usage,

    color_word('my_words', 'possible', 'hotpink')
    

提交回复
热议问题