문제

I'm trying to replace a text-node using the replaceWith() method. I can find a string within an element using the replace() method, and replace it with anything I want, but the same doesn't seem to be true of replaceWith().

FIDDLE

Why is this, and is there a way do it?

var word = 'NOT work';

var sent = $('#without').html().replace(word, 'WORK'); 
$('#without').html(sent);

$("#with "+word).replaceWith('work');
도움이 되었습니까?

해결책

.replaceWith() replaces an entire DOM element. What you are trying to do is to change the some of the text of a single text node which is part of an element. There is no single function in the DOM or in jQuery that changes just part of a text node or part of the text of an element. The only way you do that is to fetch the text, make the changes you want to it and set it back.

You could create your own jQuery method that would do that.

$.fn.replaceText = function(srcText, replacementText) {
    return this.each(function() {
        var item = $(this);
        var txt = item.text();
        item.text(txt.replace(srcText, replacementText));
    });
}

Working demo: http://jsfiddle.net/jfriend00/U8k8C/

다른 팁

Instead of .replaceWith() which replaces DOM elements, use .text('mystring') or .html('my string that may have <abbr>HTML</abbr> in it')

EDIT - I think I misunderstood what you're trying to do. It seems like you're just trying to wrap a piece of text with HTML. Your best bet is to use the .replace() function as you mentioned in your comments.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top