0

What I am trying to do here is to modify child elements and add code before and after the matched elements, then return full HTML string to update a template file.

So far this has been successful but one small problem which I can not seem to solve. for example:

var htmlObj = $('<div/>').html(html).contents();
$htmlDom    = htmlObj.parent().find('*');

$htmlDom.each(function(i, el) {
   if(typeof($(el).data('key')) !== 'undefined') {
      $(el).before(codeBefore);
      $(el).after(codeAfter);
   }
});

html = $htmlDom.html();

Now this works fine to add the code before and after. But the problem is if the markup is different for example: everything is wrapped around

This 1st line of html with is ignored unless I change to $htmlDom.parent().html(); And if there is for example additional wrap then to get this line to work I need to change to $htmlDom.parent().parent().html();

The problem is the markup will be dynamic so we don't know if the code will be wrapped or which HTML tags are used. So what I need here is a way to modify the html output to string the full markup.

tshepang
  • 12,111
  • 21
  • 91
  • 136
user828941
  • 145
  • 1
  • 9

2 Answers2

0

4hrs and no one has offered any solution for this issue.

Thankfully I was able to solve this issue using a custom outerHTML function I found here which seems to work with every type of html markup. Get selected element's outer HTML

html = $($htmlDom).outerHTML();

jQuery.fn.outerHTML = function(s) {
return s
    ? this.before(s).remove()
    : jQuery("<p>").append(this.eq(0).clone()).html();
};
Community
  • 1
  • 1
user828941
  • 145
  • 1
  • 9