0

I currently have the following JavaScript/jQuery script that gets an external html page using AJAX and runs a function on all it's text nodes.

$.get('webpage.html', function (html) {
    $(html).find('*').each(function () {
        $(this).contents().filter(function () { return this.nodeType === 3 }).each(function () {
            this.nodeValue = foo(this.nodeValue);
            console.log(this.nodeValue);
        });
    console.log(html);                      
});

However although the logged new text node values have changed and are all correct, when I try to log the html at the end I just get what I started with, the original external webpage with none of the modifications in it.

What am I doing wrong?

DLiKS

1 Answer 1

2

Writing $(html) and manipulating the results DOM tree cannot modify the original string.

Instead, you can write

var content = $('<div>' + html + '</div>');
//Modify content
html = content.html();

By wrapping the HTML in a <div>, I can easily retrieve the full source.

I wrote a more detailed explanation on my blog.

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.