2

Jquery の親 div 内の内部 div に影響を与えずに、HTML の Div 内の html を変更するにはどうすればよいですか。

これまでのところ、私はこれを持っています:

HTML:

<div id="div_to_change">
    This is the text
    <br>
    to be changed
    <div id="div_that_shouldnt_change">
       text that should not change
    </div>
    <div id="div_that_shouldnt_change2">
       text that should not change
    </div>
</div>

Jクエリ:

$("div").contents().filter(function(){ return this.nodeType == 3; }).first().replaceWith("changed text");

唯一の問題は、html にタグがなければ正常に動作することですが、たとえば<br>or<strong>などの後では変更されません。

ここでJSFIDDLE

4

1 に答える 1

2

一方通行:

$('#div_to_change').contents().each(function () {
   //select only nodes with type 3 and having a node value to ignore empty lines, format chars etc
    if(this.nodeType == 3 
        && $.trim(this.nodeValue) 
        )
    {
        $(this).replaceWith("changed text")
    }
});

デモ

またはフィルターを使用するだけです:

$('#div_to_change').contents().filter(function () {
    return (this.nodeType == 3 
            && $.trim(this.nodeValue) 
           )
}).replaceWith("changed text");

デモ

于 2013-07-09T22:50:14.967 に答える