How to create new HTML tag from jQuery

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>
<html>
    <head>
        <style type="text/css">
        .titleText {<!--from   w  ww. j  a va2 s .c o m-->
            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





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities