Wednesday 15 January 2014

javascript - How can I dynamically wrap elements in a div within another div? -



javascript - How can I dynamically wrap elements in a div within another div? -

i have next output of wordpress content:

<a href="#">link1</a> text1 <br> <br> <a href="#">link2</a> text2 <br> <br> <a href="#">link3</a> text <br> <br> <a href="#">link4</a> text4 <br> <br>

i not have access edit content i'm looking edit via jquery. need wrap each link text , br before next link in div , split in 2 columns. final result this:

<div class="col-left"> <div class="item"> <a href="#">link1</a> text1 <br> <br> </div> <div class="item"> <a href="#">link2</a> text2 <br> <br> </div> </div> <div class="col-right"> <div class="item"> <a href="#">link3</a> text3 <br> <br> </div> <div class="item"> <a href="#">link4</a> text4 <br> <br> </div> </div>

any thought how can accomplish using jquery?

i have tried using .wrap() this:

$('a').wrap( "<div class='item'></div>" );

that's pretty fun challenge.

a quick explanation... jquery appears struggle when getting text elements aren't wrapped in tag, must fist wrap them. i've used <span>. i've used code this post that.

now they're wrapped nicely, can select elements we're interested in, , find halfway point. if have odd number, let's phone call math.ceil, 1 ends in left column.

var = $('a'); var = math.ceil(a.length/2);

now let's first column , sec column elements calling $.slice.

var firstcolels = a.slice(0,i); var secondcolels = a.slice(i);

we can loop through elements , add together <div> item class. i'm using itemc1 , itemc2 can select grouped elements later on. class can have same styling.

$.each(firstcolels, function(idx,el){ $(el).nextuntil('a').addback().wrapall('<div class="itemc1"></div>'); }); $.each(secondcolels, function(idx,el){ $(el).nextuntil('a').addback().wrapall('<div class="itemc2"></div>'); });

now let's select items, , wrap of them (together) in left/right column divs!

$('.itemc1').wrapall('<div class="l"></div>'); $('.itemc2').wrapall('<div class="r"></div>';

wasn't fun? :). working fiddle.

javascript jquery html

No comments:

Post a Comment