Search code examples
jquerycsshref

jQuery - Get link, apply to other element and hide original


I have the code below. I have several iterations in fact (multiple DIVs with a class of wpdm-pro:

<div class='wpdm-pro'>
    <div class="metro-block span4 wpdm-metro mm-block-03">
        <div class="caption">
            <h4 class="media-heading" style="padding: 0px;margin:0px">TITLE</h4>
            <br/>
            <div class="btn-group">
              <a class='wpdm-download-link wpdm-download-locked btn btn-success' rel='noindex nofollow' href='http://123.com'>Download</a>
            </div>
        </div>
    </div>
</div>

The question I have is how to grab the URL, apply/wrap the heading with it and then hide the link/containing div? so it produces something like the below (logically - not physically)

<div class='wpdm-pro'>
    <div class="metro-block span4 wpdm-metro mm-block-03">
        <div class="caption">
            <a class='wpdm-download-link wpdm-download-locked btn btn-success' rel='noindex nofollow' href='http://123.com'><h4 class="media-heading" style="padding: 0px;margin:0px">TITLE</h4></a>
            <br/>
        </div>
    </div>
</div>

If there is a way to remove the <br/> tag and add it to before the link, that would be cherry on top of the cake.

This is what I have tried

<script type="text/javascript">
        $("document").ready(function () {
            $('.wpdm-download-link').each(function () {
                var theLink = $(this).attr('href');
                $(this).parentsUntil("div.caption h4").wrap("<a href='" + theLink + "'></div>");

            });
        });
    </script>

Solution

  • This snippet :

    $(".wpdm-pro").each(function(e,i) {
        var link = $(this).find('a');
        var title = $(this).find('h4');
        var newLink = link.html(title).clone();
        var caption = $(this).find('.caption');
        caption.children().not('br').remove();
        caption.prepend(newLink);
    });
    

    -- Locate link and title, add title to link and clone link. Delete anything from .caption except <br>, insert cloned link as first item to .caption --

    produces :

    <div class="wpdm-pro">
        <div class="metro-block span4 wpdm-metro mm-block-03">
            <div class="caption">
               <a class="wpdm-download-link wpdm-download-locked btn btn-success" rel="noindex nofollow" href="http://123.com">
                 <h4 class="media-heading" style="padding: 0px;margin:0px">TITLE</h4>
               </a>
               <br>
            </div>
        </div>
    </div>