このプランクでdiv
テキストを含む と、同じくテキストを含むがありますspan
。
私の目的は、 のテキストdiv
を変更せずに、 のテキストを変更することですspan
。
jQuery を試してみましたが、問題はdiv
テキスト全体が変更され、span
テキストも置き換えられてしまうことです。何かアイデアはありますか?
html
<div id="id1">some text to change <span>THIS TEXT STAYS</span></div>
ジャバスクリプト:
$( document ).ready(function() {
var id1 = $("#id1");
id1.text("New Text");
});
ベストアンサー1
これは jQuery があまり役に立たない稀な場所の 1 つです。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>
ready
または、jQuery をまったく使用しない ( 以外) 場合:
$( 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>