内部タグの内容を変更せずにdivのテキストを変更する 質問する

内部タグの内容を変更せずにdivのテキストを変更する 質問する

このプランクで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>

おすすめ記事