guerbai
guerbai

Reputation: 335

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!

Upvotes: 3

Views: 1086

Answers (3)

Mowazzem Hosen
Mowazzem Hosen

Reputation: 507

your html code is <div><span>span_text</span>div_text</div>

for your understanding I am assuming a button with id btn. clicking this button the text will be changed

button code <button id="btn">change</button>

now if you want to change all the child text of the div then the below code will work fine.

$(document).ready(function(){
    $("#btn").click(function(){
        $("div > span").text("changed_div_text");
    });
});

now if you only want to change the last child of the div then the code is below

$(document).ready(function(){
    $("#btn").click(function(){
        $("div > span:last-child").text("changed_div_text");
    });
});

hope it will solve your issue

Upvotes: 0

xianshenglu
xianshenglu

Reputation: 5309

you have to know the text div_text is the childNode of div,and it is kind of textNode

var div=document.createElement('div');
div.innerHTML='<div><span>span_text</span>div_text</div>';
div.childNodes[0].childNodes[1].textContent='test';
console.log(div.innerHTML);//<div><span>span_text</span>test</div>

if you want to change the text,you can change the value of the textNode,for example,change the textContent ,innerText or innerHTML,,,

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074088

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>

Upvotes: 3

Related Questions