JQuery/Javascript - Search DOM for text and insert HTML

后端 未结 6 1944
滥情空心
滥情空心 2020-12-06 12:44

How do I search the DOM for a certain string in the document\'s text (say, \"cheese\") then insert some HTML immediately after that string (say, \"< b >is fantastic< /

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-06 13:37

    You can use this with JQuery:

    $('*:contains("cheese")').each(function (idx, elem) {
        var changed = $(elem).html().replace('cheese', 'cheese is fantastic');
        $(elem).html(changed);
    });
    

    I haven't tested this, but something along these lines should work.

    Note that * will match all elements, even html, so you may want to use body *:contains(...) instead to make sure only elements that are descendants of the document body are looked at.

提交回复
热议问题