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
?
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 .
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.
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With