Create HTML Elements with JavaScript

You can create HTML elements directly with JavaScript /jQuery and also assign data attributes, CSS style, click handlers, classes and IDs to these elements through chaining.

Here’s an example.

var fox = $("
") .css("background", "lightyellow") .css("padding", "15px") .html("What did the fox do?") .data("color", "brown") .addClass("fox") .attr("id", "quick") .click(function () { alert("It jumped over the lazy dog!"); console.log($(this).data()); }) .append($("
")) .append( $("").html("click for the answer")); $("body").append(fox);