Dusty
Dusty

Reputation: 125

How to combine tags as long as they have the same class

The Html that I'm getting ideally looks like this:

<span class="RapidLink1-H">See the more detailed areas of what not</span>

Next my aim is to change the span tag into an anchor tag. With the ideal Html, I have done it this way:

            // Walk through each link tag on this page and replace the content with an actual link
            thisLink.each(function() {

                linkRefTarget = '';

                // Get only the identifier number of the link
                linkId = ($(this).attr('class')).replace(/[A-Za-z$-]/g, '');

                // Match this link with the list of link references
                if (thisLinkRef) {
                    for (var key in thisLinkRef) {
                        if (key == 'link' + linkId) linkRefTarget = thisLinkRef[key];
                    }
                }

                output = '';
                output+= '<a href="#' + linkRefTarget + '" id="link' + linkId + '" class="rapidLink">';
                output+= $(this).html();
                output+= '</a>';

            }).replaceWith(output);

Now, the problem comes when I'm actually getting this sort of Html (please note, I can't change the Html input):

<span class="RapidLink1-H">See the</span><span class="RapidLink1-H">more detailed areas of</span><span class="RapidLink1-H">what not</span></span>

The question is:

How could I get it to work with such a broken set of spans?

I'm thinking the following:

How could I achieve such a loop?

Thanks.

Upvotes: 1

Views: 573

Answers (1)

pimvdb
pimvdb

Reputation: 154858

There is the + selector which selects consecutive elements: http://jsfiddle.net/NWWYC/1/.

$(".RapidLink1-H + .RapidLink1-H").each(function() {
    // move contents to previous span, remove this span afterwards
    $(this).prev(".RapidLink1-H").append(
        $(this).contents()
    ).end().remove();
});

Upvotes: 3

Related Questions