How can I change an element's text without cha

2018-12-31 15:32发布

I'd like to update element's text dynamically:

<div>
   **text to change**
   <someChild>
       text that should not change
   </someChild>
   <someChild>
       text that should not change
   </someChild>
</div>

I'm new to jQuery, so this task seems to be quite challenging for me. Could someone point me to a function/selector to use?

If it is possible, I'd like to do it without adding a new container for the text I need to change.

13条回答
听够珍惜
2楼-- · 2018-12-31 16:30

Lots of great answers here but they only handle one text node with children. In my case I needed to operate on all text nodes and ignore html children BUT PRESERVE THE ORDERING.

So if we have a case like this:

<div id="parent"> Some text
    <div>Child1</div>
    <div>Child2</div>
    and some other text
    <div>Child3</div>
    <div>Child4</div>
    and here we are again
</div>

We can use the following code to modify the text only AND PRESERVE THE ORDERING

    $('#parent').contents().filter(function() {
        return this.nodeType == Node.TEXT_NODE && this.nodeValue.trim() != '';
    }).each(function() {
    		//You can ignore the span class info I added for my particular application.
        $(this).replaceWith(this.nodeValue.replace(/(\w+)/g,"<span class='IIIclassIII$1' onclick='_mc(this)' onmouseover='_mr(this);' onmouseout='_mt(this);'>$1X</span>"));
	});
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<div id="parent"> Some text
    <div>Child1</div>
    <div>Child2</div>
    and some other text
    <div>Child3</div>
    <div>Child4</div>
    and here we are again
</div>

Here is the jsfiddle of it working

查看更多
登录 后发表回答