最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JQuery: replace a string inside a div - Stack Overflow

programmeradmin4浏览0评论
<div id="content">
...
<p>NUMBER times...</p>
...
<p>Place N°: NUMBER</p>
</div>

How do I replace all NUMBER inside the content div? I tried replace method but it didn't work.

Thanks.

<div id="content">
...
<p>NUMBER times...</p>
...
<p>Place N°: NUMBER</p>
</div>

How do I replace all NUMBER inside the content div? I tried replace method but it didn't work.

Thanks.

Share Improve this question asked Feb 25, 2012 at 21:10 LauraLaura 4,3696 gold badges25 silver badges24 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 13

You can use the standard Javascript replace function for strings.

oldhtml = $('div#content').html();
var newhtml = oldhtml.replace(/NUMBER/g, "123");
$('div.demo-container').html(newhtml);

You should iterate all your text nodes and replace the text inside them.

$('#content').children().each(function() {
 var textNode = $(this);
 textNode.text(textNode.text().replace("NUMBER", "NEW"));
});

This codes assumes all the children of #content just contain text.

Try this:

$('#content').children().each(function () {
    $(this).html(function (i, html) {
        return $(this).html().replace(/NUMBER/g, '123456');
    });
});
发布评论

评论列表(0)

  1. 暂无评论