繁体   English   中英

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

[英]Changing text of div without changing its inner tag contents

在这个插件中,我有一个包含一些文本和spandiv ,也包含文本。

我的目标是更改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对你没有多大帮助的罕见地方之一。 您想直接进入该divText节点:

 $( 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> 

请看看这种方法:

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

试试这段代码,

 var id = document.getElementById('id1'); var newText = id.childNodes[0]; newText.nodeValue = 'Replaced by me '; 
 <div id="id1">some text to change <span>THIS TEXT STAYS</span></div> 

使用outerHTML

  $('#id1').html("New Text "+$('#id1 span')[0].outerHTML) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="id1">some text to change <span>THIS TEXT STAYS</span></div> 

我知道你已经接受了答案,但我认为为了多样性我可以向你展示一个jQuery解决方案:

HTML

<div id="id1">
    some text to change <span style='color:red;font-weight:bold;'>THIS TEXT STAYS</span>
</div>

jQuery 1.12.4

var $id1 = $('#id1');
var $span = $id1.find('span');
$id1.text('New Text'); // or $id1.html('New Text'); // your choice
$id1.append($span);

这可能不是最有效的解决方案,但它可以完成工作。

HTML: -

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

jQuery的: -

$( document ).ready(function() {
    var abcd = $('span').text();
    $("#id1").html("New Text "+'<span>'+abcd+'</span>');
});

我们可以通过获取跨度文本()重建整个所需的DOM

请检查更新的小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM