Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

jquery - How to change only text node in element

I have next html:

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

And I want to change label caption to Title with jquery. So I do

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

And it replaces all inner html (including abbr tag)

So, what's the easiest way to replace only Name?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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';

Demo: http://jsfiddle.net/yPAST/1/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...