0

I am trying to create an HTML document using jquery. This is the following code I want to create

<html charset=\'utf-8\'>
   <head>
   </head>
   <body>
      <table>
         <tbody>
            <tr>
               <td> sample text -1</td>
            </tr>
            <tr>
               <td> sample text -2</td>
            </tr>
         </tbody>
      </table>
   </body>
</html>

I want to create this and append it to a file. I don't want to create this using string appending. But instead it is better creating jquery elements. Tried the following:

var obj = $( 'html' );
console.log(obj.html());

Executing above code is printing the content inside html tag of present html file instead of creating a new html tag. So, is there any way to create an object of above code and stringify it? Thanks in advance

3
  • stackoverflow.com/questions/327047/… Commented Apr 5, 2018 at 4:11
  • You can only have one <html> tag on the page at any given time. Though if you want to insert elements to the page, simply use insertNode(). Commented Apr 5, 2018 at 4:17
  • Instead of string appending though, why not just use a string template? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… String templates can go multiline without appending, and you can inject varaibles into them with ${variable} Commented Apr 5, 2018 at 4:17

1 Answer 1

1
var html = $("<html>")
var head = $("<head>");
var body = $("<body>");

html.append(head);
html.append(body);

console.log(html.prop('outerHTML'));
Sign up to request clarification or add additional context in comments.

3 Comments

doing the above thing is selecting the existing elements instead of creating new elements
@rammanoj did you try it? the < > should create a new element
Yes, sorry I didn't observe the tags. Worked fine with tags. Thankyou

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.