开发者

JQuery Replace Any Text in Element with New Text

开发者 https://www.devze.com 2023-03-27 23:59 出处:网络
It\'s quite easy to find specific text with JQuery but I want to find any text within a specific element and replace it. I\'m using load() to get an element from another page so the text will vary, th

It's quite easy to find specific text with JQuery but I want to find any text within a specific element and replace it. I'm using load() to get an element from another page so the text will vary, that's why I can'开发者_开发百科t rely on using :contains().

$("#results").load('http://www.test.com/url.html .ms-bodyareaframe .ms-vb-title a', function() {
    ('.ms-vb a').html("New Text");
});

The html of the element that's being loaded is:

<td class="ms-vb">
<a>
Old Text
</a>
</td>

It doesn't matter to me if the text replacement is done within the load using a function() or if it's done separately after the page is loaded. But I've tried several ways and I have not been able to get this to work.


This is how you can find and replace values in text nodes in a manageable manner:

function findAndReplace(elements, textToFind, textToPlace) {
    $.each(elements.contents(), function () {
        // This is added to make sure the nodes you request are text nodes
        if (this.nodeType == 3)
            this.nodeValue = this.nodeValue.replace(textToFind, textToPlace);
    });
}

findAndReplace($('your element(s)'), 'textToFind', 'textToPlace');
0

精彩评论

暂无评论...
验证码 换一张
取 消