2

I have an html string from which I want to replace all my img tags with figure tag. Here is my code

$('img',$(html)).replaceWith(function(){
    var figure = '<figure><img src="'+$(this).src+'"><figcaption>'+$(this).attr('alt')+'</figcaption></figure>';
    return $(figure);
});

This code does not work. I would also like to return the resulting html string after the operation has been performed but it seems that replace only returns the element that has been replaced . So how do I do that?

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
Akshat Jiwan Sharma
  • 15,430
  • 13
  • 50
  • 60
  • you want to replace or wrap? – Arun P Johny May 31 '13 at 14:57
  • @ArunPJohny Whatever gets the job done. Basically I just want to fnd all the images in the element and repace/wrap them with a figure element and the return the html string – Akshat Jiwan Sharma May 31 '13 at 14:59
  • @NimChimpsky not a duplicate. The problem that I have here is that the html string is dynamically generated. I want the string operated upon and then returned. And the code that I am using is not working. – Akshat Jiwan Sharma May 31 '13 at 15:05
  • @AkshatJiwanSharma sorry, didn't saw you were providing the behaviour of 'not working' – A. Wolff May 31 '13 at 15:09
  • @AkshatJiwanSharma you should convert the HTML to a DOM structure, then use DOM manipulation (hence the dupe), then (optionally) serialize back. Not technically a duplicate, but close enough. – John Dvorak Jun 01 '13 at 05:50

1 Answers1

6

$(this).src isn't valid code. You need $(this).attr('src') or just this.src in this case.

However, the real problem is probably that you're expecting html to be changed in-place -- except you're not using replaceWith on html, but on $(html). In other words, your HTML string isn't being altered; your temporary jQuery object is, which then vanishes.

Try something like this:

var html = /* whatever you want */;
var $html = $(html); // jQuery object

$('img', $html).replaceWith(function () {
    return '<figure><img src="' + $(this).attr('src') + '"><figcaption>' + $(this).attr('alt') + '</figcaption></figure>';
});

html = $html.html(); // update html string, if necessary

http://jsfiddle.net/mblase75/77aXS/

Blazemonger
  • 90,923
  • 26
  • 142
  • 180