How can I get, manipulate and replace node text with jQuery?
Here is my code:
<li class="det_price"> <a href="/designer/customize/278258?dpid=1">Printing</a> from $10 </li> I have about fifteen pieces on this page, and I would like to take the text node (from $ X), select X using a regular expression, and set it to a numeric variable, then multiply it by% and add it to the original node. For example, if the original node said "from $ 10," I would like to replace it with "from $ 10 to $ 2.60." I can do this with replace () and regular expressions on a single node, but I am having trouble iterating through all of them using jQuery. Can I apply such a conversion to a jQuery object or do I need to convert it somehow and then use the standard Javascript functions?
Thanks!
Here's how to select node text.
Here (skeleton), what do you do when you have them:
$('li.det_price').contents().filter(function() { return this.nodeType == 3; }).text(function (i, text) { return text.replace(/* your schtuff here */); }); Thus, it is obvious that jQuery does not play so well with text nodes
Time to get (a little) hacks:
var rnotwhite = /\S/; // to omit text nodes that are solely white space // tweak this as needed $('li.det_price').contents().filter(function() { return this.nodeType === 3 && rnotwhite.test($(this).text()); }).text(function (i, text) { this.replaceWholeText(text + ' replaced'); // or, for more cross-browser-ness // this.nodeValue = text + ' replaced'; }); --> Check out this sweet demo <--
--> IE compatible demo here <--
Now here's the deal: if you have control over the markup, the best solution for this is to wrap the text nodes you are really interested in in <span> s, for example:
<li class="det_price"> <a href="/designer/customize/278258?dpid=1">Printing</a><span> from $10</span> </li> and then you can just do this (path less than sketch, IMO):
$('li.det_price > a + span').text(function (i, text) { return text + ' replaced'; }); $("li.det_price a").text() will provide you with the text of this LI (and, unfortunately, all the LI nodes with this class reference). To get only the text of this particular LI, you will need to assign an identifier to it or find another way to uniquely identify it.
Once you identify it uniquely, you can simply put the string in curly braces .text () to change what you had. For instance,
$("li.det_price a").text('Not Printing') will change your text above from "Print" to "Do Not Print".