Skip navigation

I’m surprised they didn’t add this feature to the core of jQuery. Oh well, here is a plug-in to create a child nodes. The plug-in also returns the nodes that were created or the jQuery object that called the function if no options were passed.

(function($) {
 $.fn.extend({
  createChild: function(options) {
   if (typeof options === "string") {
    options = { tag: options };
   }
   var settings = $.extend({}, $.fn.createChild.defaults, options);
   if (settings.tag) {
    var arr = [];
    this.each(function(i, e) {
     var elem = document.createElement(settings.tag);
     $(this).append($(elem).html(settings.html).attr(settings.attr));
     arr[i] = elem;
    });
    return $(arr);
   } else {
    return this;
   }
  }
 });
 $.fn.createChild.defaults = {
  tag: null,
  attr: null,
  html: null
 };
})(jQuery);

Example

$(function() {
  // does not create a child because no tag type was specified and
  // calling jQuery object returned
  $("div").createChild().html("welcome");

  // creates a child "span" and returns a jQuery
  // object wrapping the child that were created
  $("p").createChild("span").html("this is SPAN").createChild("hr");

  // creates a child "div" with it's html and attributes set
  $("p").createChild({ 
    tag: "div", 
    html: "hello", 
    attr: { style: "background-color: blue; color: red;"}
  });
});