如何仅更改元素中的文本节点
问题描述:
我有下一个html:
<label for="user_name">
<abbr title="required">*</abbr>
Name
</label>
我想用jquery将标签标题更改为Title
.所以我
And I want to change label caption to Title
with jquery. So I do
$('label[for=user_name]').html('Title')
它替换了所有内部html(带有abbr
标记)
And it replace all inner html (with abbr
tag)
那么,仅替换Name
的最简单方法是什么?
So, what the easiest way to replace only Name
?
答
如果使用contents()
方法,它还将返回文本节点.由于jQuery没有文本节点方法,因此将最后一个节点转换为DOM节点
If you use contents()
method it will also return text nodes. Since jQuery doesn't have text node methods, convert last node to a DOM node
$('label[for="user_name"]').contents().last()[0].textContent='Title';