Reputation: 2609
I'm having quite a bit of a problem with this, Basically I have a string that I receive from the server (Ajax). This string may or may not have an anchor link. It may also have many of them. I need to take this string, find all the anchor links, change the href and then output the result on the screen. For this I have the following code that I thought was going to work. This is as close as I've gotten so far:
result.origText = "some random text <a href=\"http://www.abc.com\">random link</a>"
after a lot of trial and error I finally came up with the following code:
var origText = $(result.origText);
origText.filter("a").each(function () {
var href = $(this).attr("href");
$(this).attr("href", href + '#ref=' + Num); //Num is currently = 12345
});
finalText = origText[0].outerHTML;
finalText
then contains:
<a href="http://www.dermapoise.com#ref=12345">random link</a>
and I've lost all the other text that was not enclosed in any tags. How can I archive this?
UPDATE: the following input strings are possible:
"some random text <a href=\"http://www.abc.com\">random link</a> some more text <a href=\"http://www.abc2.com\">random link2</a> Even more text <a href=\"http://www.abc.com\">random link3 with the same href</a>"
Upvotes: 0
Views: 414
Reputation: 388316
It is because when jQuery tries to parse the given text, it will try to parse it as a selector, other than a html content - it throws an error Uncaught Error: Syntax error, unrecognized expression: some random text <a href="http://www.abc.com">random link</a>
Since at the top level you have text nodes, it is best you wrap another container around it and then modify the contents as you need, then fetch the inner contents of the container
var origText = $('<div />').html(result.origText);
origText.find("a").attr('href', function (idx, href) {
return href + '#ref=' + Num
});
finalText = origText.html();
Upvotes: 2