Guy
Guy

Reputation: 67330

jQuery - inserted anchor tags do not wrap correctly

I have the following snippet of jQuery:

$(elementId).prevAll().appendTo(prevDiv);

It works but the problem is that all the elements selected by the prevAll() function are appended to the prevDiv div without spaces between them. This means that the content of this div (a collection of anchor tags) does not wrap onto multiple lines.

How would I add spaces after each collection item or force wrap for each element?

EDIT: As requested, here's some HTML that demonstrates the problem:

<div style="width:200px; overflow:hidden; border:2px"><a style="padding:5px;"  href="http://www.domain.com/" id="p-1">1</a><a style="padding:5px;"  href="http://www.domain.com/" id="p-2">2</a><a style="padding:5px;"  href="http://www.domain.com/" id="p-3">3</a><a style="padding:5px;"  href="http://www.domain.com/" id="p-4">4</a><a style="padding:5px;"  href="http://www.domain.com/" id="p-5">5</a><a style="padding:5px;"  href="http://www.domain.com/" id="p-6">6</a><a style="padding:5px;"  href="http://www.domain.com/" id="p-7">7</a><a style="padding:5px;"  href="http://www.domain.com/" id="p-8">8</a><a style="padding:5px;"  href="http://www.domain.com/" id="p-9">9</a><a style="padding:5px;"  href="http://www.domain.com/" id="p-10">10</a><a style="padding:5px;"  href="http://www.domain.com/" id="p-11">11</a><a style="padding:5px;"  href="http://www.domain.com/" id="p-12">12</a><a style="padding:5px;"  href="http://www.domain.com/" id="p-13">13</a><a style="padding:5px;"  href="http://www.domain.com/" id="p-14">14</a><a style="padding:5px;"  href="http://www.domain.com/" id="p-15">15</a><a style="padding:5px;"  href="http://www.domain.com/" id="p-16">16</a><a style="padding:5px;"  href="http://www.domain.com/" id="p-17">17</a><a style="padding:5px;"  href="http://www.domain.com/" id="p-18">18</a></div>

Upvotes: 3

Views: 364

Answers (3)

tvanfosson
tvanfosson

Reputation: 532545

I would change them all to be block level elements.

$(elementId).prevAll().css( { display: 'block' } ).appendTo(prevDiv);

or if you really need to append some text.

$(elementId).prevAll()
            .appendTo(prevDiv)
            .after( " " );

Upvotes: 5

chchrist
chchrist

Reputation: 19822

$(elementId).prevAll().addClass('myDisplayBlockClass').appendTo(prevDiv);

Upvotes: 0

kapa
kapa

Reputation: 78721

@tvanfosson's solution is great, but if you want to separate behaviour and presentation, add it to your CSS:

#div_you_are_inserting_to a { display: block; }

This is a choice of preference, personally I don't really like adding CSS rules to my jQuery code.

Upvotes: 2

Related Questions