2016-06-23 13 views
-1

JavaScript/JQueryを使用して、子HTMLElementsに影響を与えずにHTMLElementのテキストを変更したいです。私はinnerHTMLinnerText属性だけでなく、JQueryからhtml()方法を使用してHello, World!テキストを変更するattemtedいる子要素に影響を与えずにHTMLElementのテキストを更新する

<span class="js-my-parent-span"> 
    "Hello, World!" 
    <span class="js-my-child-span"> 
    </span> 
</span> 

は、私は次のようになりますHTMLを持っています。これらのすべてのメソッドも子のスパンであるoverwriteです。

テキストを更新したいだけです。

+0

次に、テキストノードを更新し、全体のスパンの内容を変更しようと停止します。 –

+0

'theEl.contents()。get(0).textContent = 'foo''。 'theEl [0] .childNodes [0] .textContent = 'foo'' –

+0

このディスカッションを終了する答えの1つをマークすることができます。 – Mohammad

答えて

1

テキストを独自のコンテナにラップすることができます。これはおそらく、ここでは最高のパターンです。

$('.text-content').text('Something else')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<span class="js-my-parent-span"> 
 
    <span class="text-content">Hello, World!</span> 
 
    <span class="js-my-child-span">Other content</span> 
 
</span>

+0

良い点、私は馬鹿のように感じる。これは合理的な解決策のように見えますが、htmlの変更を伴わない、より正確な解決策が誰も来なければ、私はその答えを受け入れます。 –

+1

これを行う方法は*ありますが、私はそれらを固体パターンとして提案しません –

+0

答えを見直した後、これが最も適切な解決策です。 –

1

あなたはchildNodesプロパティを使用してspanのチャイルズを得ることができます。 childNodes[0]には"Hello, World!"のテキストが含まれています。

$(".parent")[0].childNodes[0].nodeValue = "New hello world-";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<span class="parent"> 
 
    "Hello, World!" 
 
    <span>Child text</span> 
 
</span>

1

あなたは、具体的内容を保持しているテキストノードである要素の最初の子ノードをターゲットにすることができます。しかし、スパンが中文の場合、これは機能しません。

document.querySelector('button').onclick = function(){ 
 
    document.getElementById('test').childNodes[0].textContent = "It worked without changing " 
 
}
<span id="test">Change this text without removing <span>what's in the span</span></span> 
 
<button>Do It</button>

1

var childs = $(".js-my-parent-span").find(".js-my-child-span"); 
 

 
$(".js-my-parent-span").html('"Hello, world i have successfully changed only the text and not the child element!" ').append(childs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<span class="js-my-parent-span"> 
 
    "Hello, World!" 
 
    <span class="js-my-child-span">This is child span 
 
    </span> 
 
</span>

関連する問題