O'Reilly logo

jQuery and JavaScript Phrasebook by Brad Dayley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required