Generating HTML in jQuery

It’s also possible to generate code with the jQuery wrapper function. To do so, pass in a string to the jQuery function like so:

$(”<p>My nifty paragraph</p>”);

This is only half the story, because the new paragraph element added to the DOM is parentless. You’ll need an additional jQuery method like .appendTo() in order to insert the new markup into the DOM. HTML generation, coupled with selectors and chaining, allow for some very elegant jQuery statements. 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 {

color: green;

font-family:arial;

}

</style>

<script>

</script>

<script>

$(function(){

$(“<h1>Have A Nice Day</h1>”)

.appendTo(“body”)

.attr(“class”, “titleText”);

});

</script>

</head>

<body>

</body>

</html>

Code snippet is from generating-html.txt

Source: Otero Cesar, Rob Larsen (2012), Professional jQuery, John Wiley & Sons, Inc

Leave a Reply

Your email address will not be published. Required fields are marked *