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?

5
  • you want to replace or wrap? Commented May 31, 2013 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 Commented May 31, 2013 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. Commented May 31, 2013 at 15:05
  • @AkshatJiwanSharma sorry, didn't saw you were providing the behaviour of 'not working' Commented May 31, 2013 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. Commented Jun 1, 2013 at 5:50

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! @Blazemonger. Will accept in 2 minutes
I have just one question. Form my scenario Will wrap be better as one comment pointed out?
wrap will add the <figure> but you'll still need to create the <figcaption> and remove the alt attribute yourself. In the end, this code is probably simpler.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.