lapin lapin - 11 days ago 5
Javascript Question

Get string after it is changed by jQuery

I have a function which gets html as a string.

Then imagine I want to replace all link urls with a new one, without having to deal with any regex :

function myFunction(html_as_string) {
$(html_as_string).find('a').each(function() { // yes this actualy works
$(this).attr('href', 'http://some-other-link.whatever');
});
}

var html_as_string = '<div>Lorem ipsum dolor sit <a href="http://foo.com">foo</a>Lorem ipsum dolor <a href="http://bar.com">bar</a>Lorem ipsum.</div>';

myFunction(html_as_string);


Ok links' urls are virtualy changed when within the function, but how could I actualy get the new
html_as_string
variable with new urls ?

EDIT

It has to work even when there are several tag elements on the same level, eg with adding
<h1>Foo</h1>
behind the above mentioned string.

Answer

Insert the html into a temporary element, process it, and then use jQuery's .html() method to convert the container's children back to an HTML string again:

function myFunction(html_as_string) {
    var $container = $("<div />");
    $(html_as_string).appendTo($container);
    $container.find('a').each(function() { // yes this actualy works.
        $(this).attr('href', 'http://some-other-link.whatever');
    });
    return $container.html();
}

var html_as_string = '<h1>Foo</h1><div>Lorem ipsum dolor sit <a href="http://foo.com">foo</a>Lorem ipsum dolor <a href="http://bar.com">bar</a>Lorem ipsum.</div>';

console.log(myFunction(html_as_string));

Example: http://jsfiddle.net/h9sfdodx/3/

Comments