2013-07-09 116 views
2

如何在不影響Jquery中父級div內部的div的情況下在HTML中更改HTML。如何在不影響JQuery中的內部div的情況下更改html div

到目前爲止,我有這樣的:

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> 

JQUERY:

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

唯一的問題是,它是否有在HTML中沒有標籤工作正常,但例如它在<br><strong>等之後不改變。

JSFIDDLE HERE

回答

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") 
    } 
}); 

Demo

或只是過濾器:

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

Demo

+0

卓越!第二個出於某種原因在我的應用程序沒有工作,但第一個像魅力工作!非常感謝您的幫助PSL! +1 XD – vashzero

+0

嗨,我剛剛發現了一個錯誤,這可以解決嗎? http://jsfiddle.net/m5HLz/1/ – vashzero

+0

@vashzero什麼是我沒有得到它的錯誤。 – PSL

相關問題