Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change child text only with jQuery?

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!

like image 589
guerbai Avatar asked Dec 20 '25 07:12

guerbai


1 Answers

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>
like image 148
T.J. Crowder Avatar answered Dec 21 '25 23:12

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!