Wrap new div around several elements (Mootools1.2)
I recently started working at a job where they use Mootools 1.2 for their site. I am doing some new objects for their inhouse CMS-system and have run into some problems.
The system puts out this code for an object.
<div class="object_start">Title</div>
<div class="normaltext">Blahahahahaha</div>
<div class="normaltext">More text</div>
<div class="singlebox">Some content</div>
<div class="object_end></div>
I need to wrap a div around this, .... through javascript.
Since this object should be able to be present more than once on the site I've started with something like
function apply_drop() {
$$('.object_start').each(make_drop_tab_group_of_tab);
}
window.addEvent('domready', apply_drop);
to start going through each instance where an element with object_start is present.
Basically i would like to step through each element from object_start until it hits the div with class object_end and then wrap the new div around it but I just can't seem to get it right.
Anyone could give a small pointer how to easil开发者_开发百科y do this? I really do not need to transform anything more, just add the wrapper.
/Björn
The MooTools documentation is your friend. For this I'm using wraps()
and grab()
:
function apply_drop() {
var beginWrapping = false, wrapper;
// iterate over all divs
$$('div').each(function(item){
// if .object_start, wrap it in a div with class .wrapper
// and then start wrapping all elements until we hit
// a div with class .object_end
if (item.hasClass('object_start')){
wrapper = new Element('div').addClass('wrapper').wraps(item);
beginWrapping = true;
} else if (beginWrapping) {
wrapper.grab(item);
}
if (item.hasClass('object_end')) {
beginWrapping = false;
}
});
}
window.addEvent('domready', apply_drop);
in your domready:
document.getElements("div.object_start").each(function(el) {
var wrapper = new Element("div", {
"class": "wrap"
}), end = false, next;
while(!end) {
next = el.getNext(); // siblings
if (!next || next.hasClass("object_end")) end = true;
if (next) next.inject(wrapper); // will work if no object_end found gracefully.
}
// done finding siblings, now replace the orig div.
wrapper.wraps(el, "top");
});
http://jsfiddle.net/w4brx/
精彩评论