javascript - 如何更改 html div 而不影响 JQuery 中的内部 div

标签 javascript jquery

如何更改 HTML 中 Div 内的 html,而不影响 Jquery 中父 div 内的内部 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

最佳答案

一种方法:

$('#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

关于javascript - 如何更改 html div 而不影响 JQuery 中的内部 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17559532/

相关文章:

javascript - 切换全部展开/全部折叠

c# - 如何在 MVC 中实现自动完成文本框

javascript - 如何设置动画在加载下一页之前完成的延迟? [jQuery, Bootstrap ]

javascript - JQuery 计算器 : Calculate Input, 之后清除

javascript - 如何使按钮可点击但其父div?

javascript - 使用jquery更改下一个td的内容

javascript - 如何在 div 内的图像上绘制矩形框?

javascript - 如何发现哪个脚本正在控制一个元素?

javascript - 如何更正此 jquery 追加

javascript - 实时计算?