JQuery: creating new HTML snippets
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!