views:

57

answers:

4

I have a table in my markup on which I want to add some divs before and efter like this:

<div class="widebox">
<div class="widebox-header">Opret/rediger bruger</div>
<div class="widebox-middle">
<table id="Table3"></table>
</div>
<div class="widebox-bottom"></div>
</div>

I'm trying to do this with jQuery, like this:

$('#Table3').before('<div class="widebox"><div class="widebox-header">Opret/rediger bruger</div><div class="widebox-middle">');
$('#Table3').after('</div><div class="widebox-bottom"></div></div>');

However this is what renders out, the method seems to close my opening divs:

<div class="widebox">
    <div class="widebox-header">Opret/rediger bruger</div>
    <div class="widebox-middle"></div></div><!-- unexpected close divs -->
    <table id="Table3"></table>
<div class="widebox-bottom"></div>

Anyone know what could be causing this?

+2  A: 

the .before and .after methods need to describe a fully defined part of the DOM tree - that is, each call must contain both opening and closing tags - these methods add elements, not raw html, so any malformed/incomplete html you pass in with any one statement will be converted to something valid...

Check out the .wrap() method - this is what you need

http://api.jquery.com/wrap/

Graza
+2  A: 

.before() and .after() insert elements, not strings. An unclosed <div> is not a complete element, so it's automatically closed. What you want is to use the .wrap() function to wrap your new <div> around the table. E.g.:

$('#Table3').wrap('<div class="widebox-middle" />');
Max Shawabkeh
+3  A: 

before() and after() automatically close elements. Why don't try you use wrap() to insert widebox-middle around table?

$('#Table3').wrap('<div class="widebox-middle" />');
$('.widebox-middle').wrap('<div class="widebox" />');
$('.widebox-middle').before('<div class="widebox-header">Opret/rediger bruger</div>');
$('.widebox-middle').after('<div class="widebox-bottom"></div>');
mamoo
except your selectors for the widebox-middle should be `.widebox-middle` rather than `#widebox-middle` (you need to select by class rather than id)
Graza
Right! I'll change it. Thank you :)
mamoo
Thanks a lot! :)
timkl
+1  A: 

You could .wrap() the table with those divs. But in this case, I'd prefer to take the table out of the DOM, create the new DOM structure and insert it back, like:

var myTable   = $('#Table3'),
    root      = myTable.parent(),
    DOMStruct = $('<div class="widebox"><div class="widebox-header">Opret/rediger bruger</div><div class="widebox-middle"></div><div class="widebox-bottom"></div></div>');

myTable.detach();

DOMStruct.find('.widebox-middle').append(myTable);
root.append(DOMStruct);

Kind Regards

--Andy

jAndy