I’m required to basically Find and replace a list of words retrieved as an array of objects (which have comma separated terms) from a webservice. The find and replace only occurs on particular elements in the DOM, but they can have an unknown and varying number of children (of which can be nested an unknown amount of times).
The main part I’m struggling with is figuring out how to select all nodes down to textNode level, with an unknown amount of nested elements.
Here is a very stripped-down example:
Retrieved from the webservice:
[{
terms: 'first term, second term',
youtubeid: '123qwerty789'
},{
terms: 'match, all, of these',
youtubeid: '123qwerty789'
},{
terms: 'only one term',
youtubeid: '123qwerty789'
},
etc]
HTML could be something like:
<div id="my-wrapper">
<ol>
<li>This is some text here without a term</li>
<li>This is some text here with only one term</li>
<li>This is some text here that has <strong>the first term</strong> nested!</li>
</ol>
</div>
Javascript:
$('#my-wrapper').contents().each(function(){
// Unfortunately only provides the <ol> -
// How would I modify this to give me all nested elements in a loopable format?
});
The following function is very similar to cbayram’s but should be a bit more efficient and it skips script elements. You may want to skip other elements too.
It’s based on a getText function I have used for some time, your requirements are similar. The only difference is what to do with the value of the text nodes.
The function should be completely browser agnostic and should work with any conforming DOM (e.g. XML and HTML). Incidentally, it’s also very similar to jQuery’s text function.
One issue you may want to consider is words split over two or more nodes. It should be rare, but difficult to find when it happens.