0

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>
0

3 Answers 3

1

Just replace the textNode with the DIV using replaceWith()

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

FIDDLE

Sign up to request clarification or add additional context in comments.

Comments

0

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/

Comments

0

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
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.