JQuery: creating new HTML snippets

Published Sun, Jul 19 2009 22:19

Even though I’ve said that you could use the jQuery method for creating new HTML elements from strings, we still haven’t really seen how to achieve that. And that’s what we’ll do in this post. As you’ll  see, it’s really easy! We just need to pass the HTML snippet we’re interested in creating to the jQuery method. For instance, the next snippet creates a new div element with the text hello (since I’m lazy, I’ll just end up using the :

var html = $("<div>Hello</div>");

If we didn’t had any content for our div, we could even get away with less code:

var html = $("<div>");

In both cases, we’d end up with a new JQuery object which wraps the new HTML element. Unfortunately, you cannot create new script elements with this approach! (for those scenarios, you can use one of the patterns mentioned here).

As you’ve probably guessed, the power of creating new elements in this way is that you get a JQuery object and then you can use chaining for performing several actions. One of those actions is adding elements to the page’s DOM. And that’s what we’ll do in the next post. Keep tuned for more on JQuery!

Filed under:

Comments

# 9eFish said on Sunday, July 19, 2009 9:15 PM

9efish.感谢你的文章 - Trackback from 9eFish

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above:  

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Silverlight 4.0: Curso Completo

    ASP.NET 4.0: Curso Completo

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover