John
John

Reputation: 1178

Replace text inside a div without affecting any HTML tags inside of it

I see that this has been asked many times. But, unfortunately I have not come across a straight forward solution. Most solutions revolve around multiple nodes within the div.

So here's problem. I have the following markup:

<div class="test">Text1<span></span></div>

I need "Text1" to be replaced with "Text2" without affecting the span tag and event handlers attached to the span tag.

Doing something like $('.test')html('Text2<span></span>') does replace the text. But, removes the event handlers on the span tag, which is not desired. I am looking for a quick and efficient method for this one.

Upvotes: 1

Views: 1367

Answers (4)

David Thomas
David Thomas

Reputation: 253318

On the assumption that the text to be replaced will always precede the existing span, that it will always be the firstChild and that it will be an unwrapped textNode:

$('.test').click(
    function() {
        this.firstChild.nodeValue = 'Text2';
    });​

JS Fiddle demo.

To ensure that only the first textNode is changed, regardless of where it's found within the .test element:

$('.test').click(
    function(e) {
        var newText = 'Text2',
            children = e.target.childNodes;
        for (var i=0,len=children.length;i<len;i++){
            if (children[i].nodeName == '#text'){
                children[i].nodeValue = newText;
                return false;
            }
        }
    });​

JS Fiddle demo.

Upvotes: 0

Joe
Joe

Reputation: 82604

You can access the Text Node itself with contents. Now if you know that the element starts with text you can do this:

$($('.test').contents()[0]).replaceWith('New Text')​;

Now if you didn't know the location in the array of the Text Node, you can filter with:

return this.nodeType === 3;

and compare the text values (if you know those).

Fiddle

Upvotes: 3

simoncereska
simoncereska

Reputation: 3043

if you would add event handler with .live or .on functions (depends on jQuery version) .html('Text2') would work just fine.

Upvotes: 0

iambriansreed
iambriansreed

Reputation: 22241

Wrap replaceable text with a tag:

<div class="test"><span class="test-text">Text1</span><span></span></div>

Upvotes: 4

Related Questions