javascript - Chrome Extension - Add Text to First Instance of a Word or Phrase -
i'm attempting make chrome extension on load finds first instance of string , adds details, link.
from can tell treewalker best approach, i've adapted example (dom treewalker).
this works (though implementation inefficient). want effect subtle, added requirement string needs appear in paragraph cut down on chances of replacing text in menus or titles.
now behaviour erratic (some replacements made, others not).
i know .replace
implementation @ end not right solution.
any ideas?
var companies = [ "apples", "black beans", "sweet potatoes" ]; var re = new regexp(companies.join("|"), "i"); var walker = document.createtreewalker( document.body, nodefilter.show_text, function(node) { var matches = node.textcontent.match(re); //look matching text accept in paragraphs if((matches) && (node.parentnode.nodename == "p")) { return nodefilter.filter_accept; } else { return nodefilter.filter_skip; } }, false); var nodes = []; while(walker.nextnode()) { nodes.push(walker.currentnode); } node=nodes[0]; //just replace first hit within paragraph node.parentnode.innerhtml = node.parentnode.innerhtml.replace("apples", "apples [nutritional fact <a href='http://nutritionalinfo.com/apples'>apples</a> ]"); node.parentnode.innerhtml = node.parentnode.innerhtml.replace("black beans", "black beans [nutritional fact <a href='http://nutritionalinfo.com/apples'>apples</a> ]"); node.parentnode.innerhtml = node.parentnode.innerhtml.replace("sweet potatoes", "sweet potatoes[nutritional fact <a href='http://nutritionalinfo.com/apples'>apples</a> ]");
Comments
Post a Comment