在这个小混混中,我有一个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");
});
这是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] 删除。
我来说两句