Find and replace in a webpage using javascript [duplicate]

瘦欲@ 提交于 2019-11-30 08:45:28

问题


What I want to do is replace all instances of 'foo' in a webpage with 'bar' in a JS bookmarklet/greasemonkey script. How can I do this? I suppose jQuery works, as there're hacks to include those in both bookmarklets and greasemonkey scripts.


回答1:


This script iterates through each element in the document and replaces every instance of foo with bar.

The gi modifiers on the regex make it do a global, case-insensitive search.

var els = document.getElementsByTagName("*");
for(var i = 0, l = els.length; i < l; i++) {
  var el = els[i];
  el.innerHTML = el.innerHTML.replace(/foo/gi, 'bar');
}

You can target specific tag names by changing the "*" to the tag name of your choice (e.g. "p", "td").



来源:https://stackoverflow.com/questions/1155353/find-and-replace-in-a-webpage-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!