开发者

Find word on page, wrap in span tags with class

开发者 https://www.devze.com 2023-01-17 11:55 出处:网络
I would like to Find word on page, wrap in span tags with class. before proceeding to execute a javascript i have almost got ready.

I would like to Find word on page, wrap in span tags with class. before proceeding to execute a javascript i have almost got ready.

If i can work out how to just do this first part i think i can get the rest.

Find word on page, wrap in span tag开发者_StackOverflows with a class applied to the span tags. Must then be searchable via:

     $(document).ready(function(){

var injectionKey = /%id=inject%/ig;
var injectionStack = $('#%id%').html();

      (function($) {
  var theInjectionPage = $("span.myclass");
  theInjectionPage.html(theInjectionPage.html().replace(injectionKey, injectionStack)); 
})(jQuery)


    });


Do not use regex. Do not replace large chunks of innerHTML. Do not pass Go. Do not collect $200.

Walk over the text nodes only, finding the target text and splitting to insert new elements. See this question for example code using an <a>.


[See it in action]

function highlight(term, base) {
  if (!term) return;
  base = base || document.body;
  var re = new RegExp("(" + RegExp.escape(term) + ")", "gi"); //... just use term
  var replacement = "<span class='highlight'>" + term + "</span>";
  $("*", base).contents().each( function(i, el) {
    if (el.nodeType === 3) {
      var data = el.data || el.textContent || el.innerText;
      if (data = data.replace(re, replacement)) {
        var wrapper = $("<span>").html(data);
        $(el).before(wrapper.contents()).remove();
      }
    }
  });
}

function dehighlight(term, base) {
  var text = document.createTextNode(term);
  $('span.highlight', base).each(function () {
    this.parentNode.replaceChild(text.cloneNode(false), this);
  });
}

// escape by Colin Snover
// Note: if you don't care for (), you can remove it..
RegExp.escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消