问题
I'm trying to implement a text-highlighting search script on a Wordpress site for a client. The script executes a regex search on the raw HTML data from the webpage, adding a span tag/css element to any part of the document that matches the query.
However, I'm trying to search on some multi-level HTML (headers, etc), and some of the tags have descriptive id and class names, which actually end up getting found by the script and highlighted. This results in some wonky behavior when the script finds a match in one of the id names (ex: a search for "Cont" would wrap turn <div id="Container"> into <div id="<span class="highlight">Cont</span>ainer">.
This is obviously not what I want.
So, I'm wondering if there is a way to differentiate between "real text" that will show up on the page, and raw HTML, so that I can only highlight elements of the HTML that will actually be displayed.
Thanks!
回答1:
I deleted my first post to avoid the confusion, although it answered the topic question. ) But in your case a different approach should be used, I suppose:
1) get all the text nodes by...
var textNodes = $('body').find('*').contents().filter(function() {
return this.nodeType === 3 });
2) highlight the search term with some replacement op:
var term = 'xxx';
textNodes.each(function() {
var $this = $(this);
var content = $this.text();
content = content.replace(term, '<span class="highlight">' + term + '</span>');
$this.replaceWith(content);
}
来源:https://stackoverflow.com/questions/11040770/how-to-only-select-text-outside-of-a-tag-in-jquery