2012-03-31 63 views
38

我旁邊的html:如何改變只有文本節點在元素

<label for="user_name"> 
    <abbr title="required">*</abbr> 
    Name 
</label> 

我想標籤標題更改爲Title使用jQuery。所以我做

$('label[for=user_name]').html('Title') 

它取代所有內部HTML(與abbr標籤)

那麼,什麼最簡單的方法只有Name更換?

+0

看起來像**的副本[在jQuery中,如何更改元素的文本而不更改其子元素?](http://stackoverflow.com/questions/4106809)** – hippietrail 2012-10-11 09:54:00

回答

58

如果使用contents()方法也將返回文本節點。由於jQuery的沒有文本節點的方法,最後節點轉換爲DOM節點

$('label[for="user_name"]').contents().last()[0].textContent='Title'; 

演示:http://jsfiddle.net/yPAST/1/

+1

讓我們假設他沒有喜歡操縱只有1個標籤 – 2012-03-31 14:31:24

+0

有趣的..我每個輸入只有一個標籤,所以它適合我 – MikDiet 2012-03-31 18:13:50

+2

注意:'textContent'屬性* *不*在版本9之前的IE中可用。 – 2015-02-09 09:44:05

1

您可以選擇只abbr元素,儲存,然後更換整個內容與存儲的元素加改變的標題:

​$('label[for="user_name"]').each(function(){ 
    var a = $(this).children('abbr'); 
    $(this).html(a).append('Title'); 
}); 

看到這個fiddle

+0

我這樣做的方式,謝謝 – MikDiet 2012-03-31 14:12:20

2

It may not be the prettiest way, but this works:

var $label = $('label[for=user_name]'); 
$label.html($label.html().replace("Name", "Title")); 
+0

哎呀!同樣的答案我已經發布..忘了這麼多晚:( – Jigs 2012-03-31 14:04:46

+0

哈哈沒有擔心:) – 2012-03-31 14:07:10

1

可以使用replace做到這一點

var html = $('label[for=user_name]').html().replace('Name','Testing'); 
    $('label[for=user_name]').html(html); 

檢查:http://jsfiddle.net/DyzMJ/

+0

我不知道哪個標籤將..可能是'名稱',可能是別的.. – MikDiet 2012-03-31 14:11:33

1

埃文斯解決方案加入到jQuery的新生力量,使它的使用舒適:

// get/change node content not children 
jQuery.fn.content = function(n){ 
    var o = $(this).clone(); 
    var c = o.children().remove(); 
    if (typeof n === "string"){ 
     o.html(n); 
     $(this).html(c).append(n); 
    } 
    return o.html(); 
} 

使用方法:$('myselector').content('NewContentString');

34

對不起,對於遲到的回覆...但是這裏有一種方法只使用jQuery:

$('label').contents().last().replaceWith("Title"); 
+1

您保存了一天。謝謝:) – 2014-12-14 20:48:38

+1

這對我在IE10和jquery 1.4 – dxrsm 2015-06-11 07:21:49

+1

工作請注意,'replaceWith'的字符串被視爲像HTML;如果它包含標籤,它將被解析爲DOM元素。 – holmis83 2016-01-15 12:05:47

0

這是工作在大多數瀏覽器

$('label[for="user_name"]').contents().last()[0].nodeValue = 'Title'; 

這一次差點,但由於的textContent不支持

$('label[for="user_name"]').contents().last()[0].textContent='Title'; 
+0

注意:textContent屬性在版本9之前的IE中不可用。 – 2015-02-09 09:44:53

0

如果你操縱多在IE8給問題的解決1標籤你可以選擇每個標籤並用jquery替換文本:

$('label[for="user_name"]').contents().last().replaceWith("Title"); 

和第二個標籤:

$('label[for="user_lastname"]').contents().last().replaceWith("Title2"); 

等等...

相關問題