I got a piece html code like this:
<div><span>span_text</span>div_text</div>
I want to change 'div_text' with jQuery, tried with $.text('changed_div_text') but failed, result like this which is not what I want.
let tmpl = '<div><span>span_text</span>div_text</div>'
let $ = cheerio(tmpl)
console.log($.text()) // span_textdiv_text
$.text('changed_div_text')
console.log($.text()) // changed_div_text
As you can see, text() function will change inner text also, hope someone know a way to solve this problem, thanks!
jQuery doesn't offer a lot of methods that act directly on text nodes. You can use contents to find all child nodes (including text nodes), and you can use filter to find only text nodes, and then you can modify their nodeValue to change their text. Example:
// Get just the text nodes
var textNodes = $("#target").contents().filter(function() {
return this.nodeType === Node.TEXT_NODE;
});
// In this case, I just replace the text with "Index n" where n is the index
textNodes.each(function(index) {
this.nodeValue = "Index " + index;
});
<div id="target"><span>span_text</span>div_text</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With