更改div的文本而不更改其内部标签内容

ps0604:

在这个小混混中,我有一个div包含一些文本的和一个span也包含文本的。

我的目标是更改的文本div,而不更改的文本span

我尝试使用jQuery,但问题是整个div文本发生了变化,也替换了span文本,有什么想法吗?

的HTML

<div id="id1">some text to change <span>THIS TEXT STAYS</span></div>

Javascript:

$( document ).ready(function() {
    var id1 = $("#id1");
    id1.text("New Text");
});
TJ Crowder:

这是jQuery不能为您做很多事情的罕见地方之一。您想直接进入其中的Text节点div

$( document ).ready(function() {
    var id1 = $("#id1");
    // The [0] accesses the raw HTMLDivElement inside the jQuery object
    // (this isn't accessing internals, it's documented).
    // The `firstChild` is the first node within the `div`, which is
    // the text node you want to change. `nodeValue` is the text of the
    // Text node.
    id1[0].firstChild.nodeValue = "New Text";
});
<div id="id1">some text to change <span>THIS TEXT STAYS</span></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

或完全不使用jQuery(除外ready):

$( document ).ready(function() {
    var id1 = document.getElementById("id1");
    id1.firstChild.nodeValue = "New Text";
});
<div id="id1">some text to change <span>THIS TEXT STAYS</span></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章