tags:

views:

45

answers:

2

Hello all,

I tried many things but i'm asking for your help because i'm doing stupid things now ! here is what i want to do. I want to transform a html file (i'm not composing) to another. I want to move some parts of the body to div. Here is the original one :

<body>
text+images part 1
<div class="sep">some text</div>
tex+images part2
<div class="sep">some text</div>
text+images part3
</body>

and here is what i want :

<body>
<div id="div_1">
text+images part 1
</div>
<div id="div_2">
tex+images part2
</div>
<div id="div_3">
text+images part3
</div>
...
</body>

In fact the div with class="sep" will be used as separator and won't appear in the final result.

I hope i am clear and someone could help me. Best regards. Dominique.

A: 
i = 0;
$("body").contents().filter(function() {
  return this.nodeName.toLowerCase() != 'div'; // all elements but <div>s
})
.wrap(function() {
  i++;
  return $("<div />").addClass("text").attr("id", "div_"+i);
});
$(".sep").hide(); // or remove()

(see http://jsfiddle.net/FmjMx/4)

elektronikLexikon
Wow ! So fast ! And it seems so easy when i read it. A real big thanks to you. Dominique
Well after testing it's not really working because if i have some <p> tags inside body, they are not inside the new divs
then replace "return this.nodeType == 3" with "return this.nodeName.toLowerCase() != 'div'", see http://jsfiddle.net/FmjMx/4/
elektronikLexikon
The result is not exactly what i was looking for because i wanted to have all nodes before the separator div in one div and not each node in different div. But i still want to give you a big thanks because i learned something new for me and very usefull.
A: 

Now I finally found a solution:

$("body").prepend('<div class="sep">some text</div>');
$('.sep').each(function(i){
    var $set = $();
    var nxt = this.nextSibling;
    while(nxt) {
        if(!$(nxt).is('.sep')) {
            $set.push(nxt);
            nxt = nxt.nextSibling;
        } else break;
    }
   $set.wrapAll('<div class="text" id="div_'+i+'"/>');
});
$(".sep").hide(); // or remove

(see http://jsfiddle.net/sK2xN/1/ and SO: jQuery wrapping text and elements between <hr> tags.)

elektronikLexikon
Wow again ! I don't know if i can say Thanks again ? ... Well, A big thanks to you ! I hope I will be able to help others like you did with me in the near future. Thank you. Dominique.
I know how you could thank me: accept my answer :-)
elektronikLexikon