user1320260
user1320260

Reputation:

jQuery - Replace text with text plus html element

I have some text I wish to replce using jquery. the problem is, is that this text is not within it's own element, the content is dynamic and I can not access HTML the markup to make things easier.

I can detect and replace the text in question, but I have only managed to replace it with a new text node, therefore it treats my html tags as text and not markup

DEMO http://jsfiddle.net/XvTgP/

$('div.myDiv').contents().filter(function () {
    return this.nodeType == 3
}).each(function () {
    this.textContent = this.textContent.replace('my old text no in its own element', '<div class="newClass">my new text</div>');
    var myNewNode = this.textContent;
    return
});

CURRENT OUTPUT AS TEXT

<div class="newClass">my new text</div>

Upvotes: 0

Views: 670

Answers (3)

kpblc
kpblc

Reputation: 902

if i correctly understand question

$('div.myDiv').contents().filter(function () {
    return this.nodeType == 3
}).each(function () {
    this.textContent = this.textContent.replace('my old text no in its own element', '<div class="newClass">my new text</div>');
    var myNewNode = this.textContent;
    var myParentNode = myNewNode.parent();
    myParentNode.append(myNewNode);
    return
});

Upvotes: 0

Surreal Dreams
Surreal Dreams

Reputation: 26380

Try adding html when you assign the HTML content:

$('div.myDiv').contents().filter(function () {
    return this.nodeType == 3
}).each(function () {
    this.textContent.html = this.textContent.replace('my old text no in its own element', '<div class="newClass">my new text</div>');
    var myNewNode = this.textContent;
    return
});

I think you can simplify a bit more:

$('div.myDiv').contents().filter(function () {
    return this.nodeType == 3
}).each(function () {
    this.html(this.textContent.replace('my old text no in its own element', '<div class="newClass">my new text</div>'));
});

Here's a jsfiddle showing that it works: http://jsfiddle.net/XvTgP/5/

Upvotes: 0

adeneo
adeneo

Reputation: 318342

Just replace the textNode with the DIV using replaceWith()

$($('div.myDiv div').get(0).nextSibling).replaceWith('<div class="newClass">my new text</div>');

FIDDLE

Upvotes: 1

Related Questions