nbro
nbro

Reputation: 15837

How to replace only text content on an element?

I have the following structure:

<li>
    <a><i>...</i>Some Text Here!</a>
    <input>
    <a></a>
</li>

I want just to change the string Some Text Here! under the element li without affecting (removing or changing) anything else, that is all its child nodes.

Apparently, textContent, if set, removes all descendant elements. Other similar methods seem to do the same thing. I have searched for a while, but no solution seems to solve this.

I can set classes or ids to whatever element you see in the structure, if that helps.

Upvotes: 3

Views: 4589

Answers (4)

paulitto
paulitto

Reputation: 4673

You can also get the element contents and check each nodeType to be a TEXT_NODE

Jquery version:

$('a').contents().filter(function () { 
    return this.nodeType === Node.TEXT_NODE; 
})
.each(function () { 
    this.nodeValue = 'Something else'; 
});

Javascript version:

var nodes = document.getElementsByTagName('a')[0].childNodes;
for (var i in nodes){
    if (nodes[i].nodeType === Node.TEXT_NODE)
        nodes[i].nodeValue = 'Something else';
}

Upvotes: 2

Sebastian Simon
Sebastian Simon

Reputation: 19485

Use Element.childNodes which covers text nodes along with elements and replace their textContent:

document.getElementsByTagName('a')[0].childNodes[1].textContent='Something else';

It obviously depends on how many tags there are, whether there are spaces between them, which text you want to replace, etc.


A demo:

document.getElementsByTagName('p')[0].childNodes[1].textContent = ' Something else.';
<p><i>I’m an element.</i> Some Text Here!</p>

Upvotes: 1

Buzinas
Buzinas

Reputation: 11725

Supposing you already have the <a> tag in a variable anchor:

anchor.lastChild.textContent = 'My text';

Look at the example below:

var anchor = document.querySelector('a');
anchor.lastChild.textContent = 'Other text';
<li>
    <a><i>Lalala...</i>Some Text Here!</a>
    <input>
    <a></a>
</li>

Upvotes: 1

AJB
AJB

Reputation: 7592

You can't. Corrected.

However, for cleanliness sake you should wrap the text in a span and then replace the contents of the span. It's much easier to read, like so:

HTML

<li>
  <a><i>...</i><span class="replace-me">Some text here!</span></a>
</li>

jQuery

$('.replace-me').text('Some new text here now!');

Upvotes: 0

Related Questions