JS implement query keyword, make it highlight

Source: Internet
Author: User

Today do a function: on the page to query the key, so that it highlighted, the implementation code is as follows:

Css:

   <style type= "Text/css" >        . Highlight        {            background-color: yellow;        }     </style>

Javascript:

 functionHighlight () {clearselection ();//first, clear the last highlighted content;            varSearchText = $.trim ($ (' #txtKeyWord '). Val ());//get the keywords you typed;            if(Searchtext.length > 0) {                varREGEXP =NewREGEXP (SearchText, ' G ');//Create a regular expression, g means global, if not G, then find the first one will not continue to look down;                $(' #dialogue. DHC '). each (function()//traverse the area to be queried;                {                    varHTML = $ ( This). html (); varnewhtml = Html.replace (RegExp, "<span class= ' highlight ' >" + searchtext + ' </span> ');//Replace the Found keyword, plus the highlight attribute;                    $( This). HTML (newhtml);//updated articles;                }); }            //Prekeyword = SearchText;        }        functionClearSelection () {$ (' #dialogue. DHC '). each (function()//Traverse            {                $( This). Find ('. Highlight '). each (function()//Find all elements of the highlight attribute;                {                    varthishtml = $ ( This). html (); $( This) [0].outerhtml =thishtml; //$ (this). ReplaceWith (thishtml);//remove their attributes;                });        }); }

JS implement query keyword, make it highlight

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.