JQuery/Javascript - Search DOM for text and insert HTML

后端 未结 6 1946
滥情空心
滥情空心 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:18

    Works in all browsers except IE I think, need confirmation though.

    This supports content in iframes as well.

    Note, other examples I have seen, like the one above, are RECURSIVE which is potentially bad in javascript which can end in stack overflows, especially in a browser client which has limited memory for such things. Too much recursion can cause javascript to stop executing.

    If you don't believe me, try the examples here yourself...

    If anyone would like to contribute, the code is here.

    function grepNodes(searchText, frameId) {
      var matchedNodes = [];
      var regXSearch;
      if (typeof searchText === "string") {
        regXSearch = new RegExp(searchText, "g");
      }
      else {
        regXSearch = searchText;
      } 
      var currentNode = null, matches = null;
      if (frameId && !window.frames[frameId]) {
        return null;
      }
      var theDoc = (frameId) ? window.frames[frameId].contentDocument : document;
      var allNodes = (theDoc.all) ? theDoc.all : theDoc.getElementsByTagName('*');
      for (var nodeIdx in allNodes) {
        currentNode = allNodes[nodeIdx];
        if (!currentNode.nodeName || currentNode.nodeName === undefined) {
          break;
        }
        if (!(currentNode.nodeName.toLowerCase().match(/html|script|head|meta|link|object/))) {
          matches = currentNode.innerText.match(regXSearch);
          var totalMatches = 0;
          if (matches) {
            var totalChildElements = 0;
            for (var i=0;i= 0; i--) {
            previousElement = matchedNodes[i - 1];
            if (!previousElement) {
              continue;
            }
            if (previousElement.nodesYetTraversed !== 0 && previousElement.numMatches !== previousElement.childElementsWithMatch) {
              previousElement.childElementsWithMatch++;
              previousElement.nodesYetTraversed--;
            }      
            else if (previousElement.nodesYetTraversed !== 0) {
              previousElement.nodesYetTraversed--;
            }               
          }
        }
      }
      var processedMatches = [];
      for (var i =0; i <  matchedNodes.length; i++) {
        if (matchedNodes[i].numMatches > matchedNodes[i].childElementsWithMatch) {
          processedMatches.push(matchedNodes[i].node);
        }
      }
      return processedMatches; 
    };
    

提交回复
热议问题