Help with manipulating child/parent elements with jQuery

Posted by Mohammad on Stack Overflow See other posts from Stack Overflow or by Mohammad
Published on 2010-05-27T16:27:25Z Indexed on 2010/05/27 17:21 UTC
Read the original article Hit count: 238

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>
</a>

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* (works but looks sloppy) I'm editing it atm;

if(img.parent('a').length){
    var targetLink = img.parent().attr('href');
    img.parent().wrap('<div class="photo"></div>');
    var divTarget = img.parent('a').parent('div');
    divTarget.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>");
};

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery