$("html tags")

In this chapter you will learn:

  1. How to generate code with the jQuery wrapper function.

jQuery wrapper function

We can pass in a string to the jQuery function to create new HTML tags:

$("<p>My paragraph</p>");

You need an additional jQuery method like .appendTo() in order to insert the new markup into the DOM.

The following code sample shows HTML generation, coupled with .appendTo() and .attr() used to insert a new H1 into the page.

<!DOCTYPE html><!--from  java2s  .  c o m-->
<html>
    <head>
        <style type="text/css">
        .titleText {
            color: green;
            font-family:arial;
        }
        </style>
        <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
        <script>
            $(function(){
                $("<h1>This is a header</h1>")
                .appendTo("body")
                .attr("class", "titleText");
            });

        </script>
    </head>
    <body>
    </body>
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. Syntax and Description for .add() DOM method
  2. How to add element to a paragraph
  3. How to add new tags
  4. How to chain add method with other methods