Currently I have this JQuery script
var img = $(this);
img.wrap('<div class="photo"></div>');
img.parent().append("<p>" + img.attr("alt") + "</p>");
which successfully turns the following:
<img src="photo.jpg" alt="caption">
into this
<div class="photo">
<img src="photos.jpg" alt="caption"/>
<p>caption</p>
</div>
All is well unless the image has a link as a parent; <a href="#"><img
since I want it to be correct html (I'm fussy) improving the resulting outcome bellow would be satisfactory
<a href="#">
<div class="photo">
<img src="photos.jpg" alt="caption"/>
<p>caption</p>
</div>
</a>
to this:
<div class="photo">
<a href="#">
<img src="photos.jpg" alt="caption"/>
</a>
<p><a href="#">caption</a></p>
</div>
This is my jQuery script so far (which doesn't work bc I'm a noob) aha
if(img.parent('a')){
var targetLink = img.parent('a').attr('href').val();
img.parent('a').wrap('<div class="photo"></div>');
img.parent('div').append('<p><a href="'+targetLink+'">' + img.attr("alt") + '</p></a>');
}else{
img.wrap('<div class="photo"></div>');
img.parent().append("<p>" + img.attr("alt") + "</p>");
};
Any advice, or help will be greatly appreciated : )
Thank You!
Update *Answer*
var withLink = img.parent('a').length > 0,
targetPar = withLink ? img.parent() : img;
targetPar.wrap('<div class="photo"></div>');
if(withLink > 0){
targetPar.parent().append('<p class="caption"><a href="'+img.parent().attr('href')+'">' + img.attr('title') + '</p></a>');
}else{
img.parent().append('<p class="caption">' + img.attr('title') + '</p>');
}