0

I have list of articles with 3 elements inside. A div, a h3 and a p. Within the div is an image, the h3 is a href and the text with the p. The content is different within each article.

I need to take the href from the h3 and wrap around the div, h3 and p. They have no unique identifiers. The only classes are on the initial article and the div which are the same throughout.

I'm hoping that I can take the content of the href as a variable, remove that href leaving the link intact as text and then rewrite the href with the variable wrapping the 3 elements.

Any help would be appreciated, I hope I've explained it fully enough. The markup follows.

<article class="summary">
    <div class="article-image">
        <img alt="" src="https://funeralzone.co.uk/assets/uploads/images/Funeral%20Costs(1).jpg" style="width: 255px; height: 169px;">
    </div>
    <h3>
        <a href="funeral-organiser/how-to-guides/a-guide-to-funeral-costs">A Guide to Funeral Costs</a>
    </h3>
    <p>How much does the average funeral cost? Where can you get help?</p>
</article>
4

2 回答 2

4

Here you go :) http://jsfiddle.net/k9ksn/

$('.summary').each(function () {
    var href = $(this).find('a').attr('href');
    var anchorInner = $(this).find('a').text();
    $(this).find('h3').html(anchorInner);
    $(this).wrapInner('<a href="'+href+'"></a>');
});
于 2013-10-17T18:14:28.783 回答
0

If I understood, you're trying to wrap the whole article item in a link which href is the one on the hyperlink within the h3, and replace this link with common text (span).

Try this way:

$(function () {
    $("div.article-image").each(function () {
        var link = $(this).next("h3").find("a");
        var linkHref = $(link).attr("href");
        var linkText = $(link).html();        
        var wrapper = $("<a />", {
            href: linkHref
        });
        var linkAsText = $("<span />").html(linkText);

        $(this).parent().append($(wrapper));

        $(wrapper).append($(this).parent().children());

        $(link).replaceWith($(linkAsText));
    });
});

Demo: http://jsfiddle.net/JpArk/2/

于 2013-10-17T18:16:13.040 回答