Can jQuery be used as a live html parser/ node replacement utility?
Each of my posts have a different keyword they are optimized for. I need a routine that will take the post content and wrap the first instance of 开发者_开发百科my keyword in strong tags. I don't want to decorate the keyword if its (1) part of an element's attribute collection (title, src, alt, etc). And I don't want to decorate it if its in a h1-6 heading tag.
I know there are lots of tools for dom traversal and Html parsing/replacement. Can jQuery do this?
Can someone give any examples of using jQuery as html parser?
This might be what your looking for. You shouldnt be parsing the HTML directly. it's better to traverse the DOM and look for text nodes.
var word = "foo";
var nodes = $("postSelector").find("*"); // get all elements
for (var i = 0; i < nodes.length; i++) {
// get the node
var node = nodes.eq(i);
// if the tagName is a h1-h6 then continue
if (/h\d/.test(node[0].tagName)) continue;
if (node.text().indexOf(word) > -1) {
// handle the textual replacement.
var text = node.text();
text.replace(word, "<strong>" + word + "</strong>");
node.html(text);
}
}
This will cause problems if you have nested html with your words like
<p> fo <span> o </span> </p>
That's a completely different issue to solve though.
精彩评论