TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Ask HN: Efficient HTML Text Replace, RegEx? jQuery?

2 pointsby jdavidalmost 15 years ago
[disclaimer] I understand the risk in using a framework, but I also understand the benefits. I was only using jQuery to see if it was a fast enough approach.<p>So, the other day, i wrote a line of jQuery like so to find all elements that contained the word 'apple'. the idea was that i could do the find/replace faster than doing it via a regex over the whole doc, which requires a redraw.<p>$("*:contains['apple']").each( function(){ //do something });<p>the result was that i was processing iteratively on every item in the DOM that had a descendant which contained the word 'apple', rather than just the child objects.<p>I ended up using some code from Johann Burkard http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html<p>Johann's approach iterates through the text using a string.indexOf(pat) pattern. i was wondering if any of you had any better ideas?<p>In the ideal situation, i would use a jQuery selector to select only child nodes that contained 'apple', but there is no such selector 'isChild' that can be paired with :contains as far as i know.<p>I would like to replace all instances of 'apple' with '&#60;span class="highlight"&#62;apple&#60;/span&#62;" with the lowest impact to the dom possible.

1 comment

byoung2almost 15 years ago
<i>but there is no such selector 'isChild' that can be paired with :contains as far as i know</i><p>Maybe you can use $.children()? Something like:<p><pre><code> $('div').children(":contains('apple')").each(function() { var html = $(this).html().replace(/apple/,"&#60;b&#62;apple&#60;/b&#62;"); $(this).html(html); }); </code></pre> example: <a href="http://www.fillerspace.com/apple.html" rel="nofollow">http://www.fillerspace.com/apple.html</a>
评论 #1559835 未加载