Skip to content Skip to sidebar Skip to footer

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 he

Solution 1:

Wrap replaceable text with a tag:

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

Solution 2:

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


Solution 3:

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


Solution 4:

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.


Post a Comment for "Replace Text Inside A Div Without Affecting Any HTML Tags Inside Of It"