How to change child text with jQuery only?

I have a piece of html code:

<div><span>span_text</span>div_text</div>

I want to change the "div_text" using jQuery, having tried using $ .text ('changed_div_text'), but it didn’t work, it turned out that this 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, the text () function will also change the inner text, hope someone knows a way to solve this problem, thanks!

+4
source share
3 answers

jQuery , . contents ( ), filter , nodeValue, . :

// 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>
Hide result
+3

, div_text - childNode div, 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>

, textNode, , textContent, innerText innerHTML,,

0

html <div><span>span_text</span>div_text</div>

. btn. ,

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

, div, .

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

, div,

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

, .

0

Source: https://habr.com/ru/post/1693447/


All Articles