javascriptjqueryreplacewith

jQuery.wrap where contents not a direct descendant


I am trying to wrap selected nodes in a non-trivial structure, where the node will not (necessarily) be a direct descendant. It seems that wrap() is insufficient to use in a one-liner.

I got it to work using replaceWith, using placeholder syntax to replace the original HTML. The following works fine and could easily be wrapped in a jQuery plugin. But I am curious if there is a better solution.

var template = '<div>\
                  <div>...</div>\
                  <div>{{original}}</div>\
                  <div>...</div>\
                </div>';

$('p').each(function() {
  var o = $(this).html();
  $(this).replaceWith(template.replace('{{original}}', o));
});

Solution

  • For more complex templates, you will want to look into the jQuery Template Plugin. It's still in beta, but it looks like it should provide a lot of flexibility. My original solution is still more compact, but using the jQuery.tmpl() function is close to a workable solution.

    For the simpler cases, as described above, you're probably better off wrapping it in a 2-line plugin, like so:

    $.fn.templateWrap = function(template) {
      return this.each(function() {
        var o = $(this).html();
        $(this).replaceWith(template.replace('{{original}}', o));
      });
    }
    

    Then call it using:

    $('#target').templateWrap('<div>...{{original}}...</div>');
    

    (Download jquery.templatewrap.min.js)