1

I have a comma separated list of links like this:

<a href="#">link</a>,
<a href="#">link</a>,
<a href="#">link</a>,
<a href="#">link</a>,
<a href="#">link</a>,
<a href="#">link</a>
<div></div>

Now I would like to wrap the links from position 3 to the last so that it looks like:

$("a").eq(1).nextUntil("div").wrapAll('<span>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#">link</a>,
<a href="#">link</a>,
<span>
    <a href="#">link</a>,
    <a href="#">link</a>,
    <a href="#">link</a>,
    <a href="#">link</a>
    </span>
<div></div>

I tried it like this:

    <a href="#">link</a>,
    <a href="#">link</a>,
    <span>
    <a href="#">link</a>,
    <a href="#">link</a>,
    <a href="#">link</a>,
    <a href="#">link</a>
    </span>
    <div></div>

However, this does not wrap the commas and the result looks as follows:

<a href="#">link</a>,
<a href="#">link</a>,
<span>
    <a href="#">link</a>
    <a href="#">link</a>
    <a href="#">link</a>
    <a href="#">link</a>
    </span> ,,,
<div></div>

How can I include the commas in the nesting?

Demo: http://jsfiddle.net/aa9GJ/1/

1
  • Not sure of the answer to this one, but I can see why it's doing it. The wrapAll wraps the anchors, but the commas are not inside the anchors so they get pushed outside the span. I'll have a think and then come back and find someone has answered it for you :p Commented Feb 16, 2014 at 20:33

2 Answers 2

1

Okay, I finally figured something out. You select the first element you want inside the span, and then you parse the DOM and make an element array yourself, rather than letting jQuery do it. Then you can wrap the array as you have done and it will include the commas...

$("a").eq(2).each(function(){
    var $elements = $(this);
    var next = this.nextSibling;
    while (next) {
        if ($(next).is("div")) {
            break;
        } else {
            $elements.push(next);
            next = next.nextSibling;
        }
    } 
   $elements.wrapAll('<span>');
});

Working jsfiddle example...

Sign up to request clarification or add additional context in comments.

Comments

0

try this:

$("a").eq(1).nextUntil("div").wrapAll('</a>');

if thats what you want - i believe you want it after each list right??

3 Comments

I fail to see how that would solve my problem. The wrapping element should be a span and wrapAll does not include the commas.
can you be more specific on what your trying to accomplish?? because this would give you "list,list,list,list,list"
give an example of your ideal output

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.