Question

I was trying to improve my website adding parts that will be there in every page and automatically update as i update a file: i know there are many methods but I'm still a beginner and i decided to use jQuery. The problem is that i use a <table> because I have a bar div that needs to be on the side of what's in the HTML. I prepended the header, the opening tags of the table (including tr and td) and their content and appended the closing of the tags. The HTML contained whatever staid near the bar: and it does! But it's under the bar: I'm not really sure what happened: my thought was that XHTML was closing the tags automatically before appending since in the HTML it didn't find them... I'll include the code that we're interested it

$(document).ready(function(){
    $('body').prepend('<table><tr><td>Text</td><td>');
    $('body').append('</td></tr></table>');
})

That is the jQuery code and i can ensure you i have proper links to the script and to jQuery (+UI) which work. Now everything should be simple: you just add your HTML code in the of the .html file... But nope!

<html>
   <head>
      <title>Cheese</title>
      <script to my script and jQuery library/>
   </head>
   <body>
      <!-- here should go what I prepended, and it does,
           but closes the <table></td></tr> tags aswell -->
      This should be to the side of 'Text' and comprehended in the table, in a td
      <!-- here should go what I appended,
           but strangely it doesn't -->
   </body>
</html>

Have I done anything wrong? if you don't see anything wrong here I'll send you all of the code, thank you in advance!

Was it helpful?

Solution

You cannot append/prepend/insert tags into the DOM only complete html elements. When you pass partial fragments of html to be inserted into the DOM the browser(or maybe jquery) does the best it can with it.
What you should do is build a table with the descried content and insert that to the dom

$(document).ready(function(){
    $('body').html('<table><tr><td>Text</td><td>'+$('body').html()+'</td></tr></table>');
})

http://jsfiddle.net/yY92d/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top