Search code examples
jqueryhighlighting

using jquery, how to highlight search term in ajax response HTML content


I am seeing plenty of libraries and plugins for finding a search term in a regular page, but they are not written to handle highlighting a string within ajax response content. E.g. many scripts I find do the call to the main function like for example:

`returnDataSearchTermHighlightified = highlight(searchString);`

(^^^ from the accepted answer at: Highlight search terms (select only leaf nodes))

...where that highlight() function's missing second param is auto-populated with the entire HTML body of the page. But in my case I am not wanting to highlight keywords in the parent body, but in the ajax response content only (a div I populate in the parent body), and so I cannot do e.g. this:

returnDataSearchTermHighlightified = highlight(searchString);

...and if I try this:

...
var jqxhr = $.ajax(

        {
            type: 'POST',
            url: ajaxWorkerSourceUrl,
            data: form_data,
            timeout: 15000
        }
    )
    .success(function(returnData) {
        $("#ajaxSpinner").fadeOut('slow');
        searchString = 'example';
        returnDataSearchTermHighlightified = highlight(searchString, returnData);

...then the page seems to load my ajax response with no error, but that response content is empty! Can anyone point me to fixing this? .. or even to a library or plugin designed to handle keyword highlighting in jquery ajax response content?

Thanks!


Solution

  • It seems that function highlight(term, base) requires base to be of type Element or jQuery .

    Try

    .success(function(returnData) {
            $("#ajaxSpinner").fadeOut('slow');
            var searchString = 'example',
                base = $(returnData);
            highlight(searchString, base);
            base.appendTo(document.body); //whatever you were going to do..