Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change only text node in element

Tags:

jquery

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?

like image 364
mikdiet Avatar asked Mar 31 '12 13:03

mikdiet


People also ask

How do I get nodes in text?

To get the text node of an element with JavaScript, we can use the document. createNodeIterator method to iterate through all the text nodes. to select the p element with document. querySelector .

How do you change text in TextNode?

If you have a specific node (of type #text) and want to change its value you can use the nodeValue property: innerText (and possibly textContent) will return/set both the current node and all descendent nodes text, and so may not be the behaviour you want/expect.

What is the text node?

A text node encapsulates XML character content. A text node can have zero or one parent. The content of a text node can be empty. However, unless the parent of a text node is empty, the content of the text node cannot be an empty string.

How do you get text tags in html?

Use the textContent property to get the text of an html element, e.g. const text = box. textContent . The textContent property returns the text content of the element and its descendants. If the element is empty, an empty string is returned.


1 Answers

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/

like image 121
charlietfl Avatar answered Sep 17 '22 14:09

charlietfl