PDA

Pogčedajte punu verziju : jQuery, wrap arround selection


Ilija Studen
22. 03. 2007., 12:39
Imam jedan mali problem. Naime, želeo bih ovaj kod:

<fieldset>
<legend>Legend</legend>
<p>First paragraph</p>
<div>Some crazy stuff here</div>
<br />
Ma jeste...
</fieldset>

Da transformišem u sledeći oblik:

<fieldset>
<legend>Legend</legend>
<div class="fieldsetBody">
<p>First paragraph</p>
<div>Some crazy stuff here</div>
<br />
Ma jeste...
</div>
</fieldset>

Problem je što wrap() funkcija prođe preko svakog selektovanog elementa, a meni treba da wrapuje grupu.

Any ideas?

ivanhoe
22. 03. 2007., 13:49
postoji u DOM specifikaciji document.createDocumentFragment(); koji sluzi za manipulaciju sa vise nodova odjednom, ali ne znam kakva mu je podrska u IE..

postoji jednostavnije resenje, dodaj novi div element u fieldset, pa onda pomeri paragraf i div sa textom u taj novi div...

Ilija Studen
22. 03. 2007., 14:57
Problem rešen. Samo kreiraš DIV i dodaš mu podelemente. Evo ga kod koji radi posao (za sada sam stigao sam dotle, malo me omeo 300 (http://www.imdb.com/title/tt0416449/) u radu ;) ):

jQuery.fn.collapsible = function() {
return this.each(function() {
var fieldset = jQuery(this);
var legend = fieldset.find(':first');
var body = jQuery(document.createElement('div'));

body.addClass('collapsibleFieldsetBody');
body.append(fieldset.find('*:gt(0)'));

legend.addClass('collapsibleFieldsetTitle');

legend.after(body);
});

return this;
}

Ilija Studen
22. 03. 2007., 15:20
Sorry što se svađam sam sa sobom ali kod gore ima jednu grešku pa da ne bude kako širim dezionformacije :D Naime, stari kod izvuče SVE podelemente i strpa ih u novi DIV ignorišući strukturu. U tom kodu će:

<p>Hello <b>there</b>.</p>

Biti transformisano u:

<p>Hello .</p>
<b>there</b>

No, evo ga fix. Mnogo je jednostavnije IMO:

jQuery.fn.collapsible = function() {
return this.each(function() {
var fieldset = jQuery(this);
var legend = fieldset.find(':first');
var body = jQuery(document.createElement('div'));

var children = fieldset.children();
var len = children.length;
if(len > 1) {
for(i = 1; i < len; i++) {
body.append(children[i]);
} // for
} // if

body.addClass('collapsibleFieldsetBody');
legend.addClass('collapsibleFieldsetTitle');

legend.after(body);
});

return this;
}

nixa
22. 03. 2007., 16:56
Spartans! Enjoy your code, for tonight we dine in Hell!