FidoBoy
FidoBoy

Reputation: 392

Replace returned data from a jQuery ajax call before show it

It should be pretty simple, but i'm going crazy on this issue. Basically what i'm trying to do is to replace some tags from returned HTML data before display it on the page. For example:

$.ajax({
    url: url,
    cache: false,
    type: 'GET',
    success: function(data) {
        // Here i need to replace href in ALL <a> tags and add the onclick attrib with the contents from the href 
        $('#floaty-dialog').html(modifieddata);
    }
});

how can i pre-process the HTML data and replace all href attributes with # and add a onclick attrib to that same links??

Upvotes: 2

Views: 912

Answers (1)

Julien Royer
Julien Royer

Reputation: 1429

I would use the browser's HTML parser to do the work for me:

var dom = $(data);
dom.find("a").each(function() {
  var href = this.href;
  $(this).click(function(e) {
    e.preventDefault();
    alert(href);
  });
}).attr("href", "#");

$('#floaty-dialog').html(dom);

Upvotes: 1

Related Questions