Creating HTML Elements Using jQuery

var newP = $('<p id="newp" class="nice">new P</p>'); var img = $("<img></img>"); img.attr("src", "images/newImg.jpg"); var opt = $("<option></option>"); opt.html("Option 1"); opt.val(1); opt.attr("selected",true):

An extremely important aspect of jQuery is the ability to create HTML elements from an HTML string. To create an HTML object from a string, simply call jQuery(htmlString) or $(htmlString). The string can include attribute settings and content. For example:

var newP = $('<p id="newp" class="nice">new Paragraph</p>');

Notice that I used single quotes to define the htmlString. That allowed me to put in the id="newp" and class="nice" ...

Get jQuery and JavaScript Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.