0

I am loading a html file with jquery $.get and wrap the response. But jQuery removes my wrapper .

I made the following example which demonstrates my problem: https://jsfiddle.net/pwm76bp6/

Everyone who dont want to open the link here is the example code:

alert($('<div><div>Hallo</div></div>').html());

I would expect that the whole string should be alerted. Whats the problem here?

tiktak
  • 57
  • 10
  • Possible duplicate of [Get selected element's outer HTML](http://stackoverflow.com/questions/2419749/get-selected-elements-outer-html) – str Jun 28 '16 at 08:24
  • Why not `alert('
    Hallo
    ');`. And, if you need insert that HMTL: `document.getElementById('receptor_id').innerHTML = '
    Hallo
    ';`.
    – José M. Carnero Jun 28 '16 at 08:27

5 Answers5

2

You need to read outerHTML property.

console.log($('<div><div>Hallo</div></div>').prop('outerHTML'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
dippas
  • 58,591
  • 15
  • 114
  • 126
Satpal
  • 132,252
  • 13
  • 159
  • 168
0

Dynamically wrap it with an element, then get the html() of the wrapped element.

alert($('<div><div>Hallo</div></div>').wrap("<div></div>").parent().html());
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
0

It doesn't remove your wrapper. jQuery html() does return the contents of an element.

When you do $('<div>my content</div>') you creating an element, then you get the inner html with html() which is then alerted in your example.

malifa
  • 8,025
  • 2
  • 42
  • 57
0

With your code you will get the html of your outer element <div>. And the content of the outer <div> is <div>Hallo</div>.

You can do what you want with a default property:

alert($('<div><div>Hallo</div></div>')[0].outerHTML);
eisbehr
  • 12,243
  • 7
  • 38
  • 63
0

the function "html" does return the html content of a given element. In your case "html()" returns the content of the outer div, which excludes the outer itself.

You may can overcome this by wrapping your html like:

var html = '<div><div>Hallo</div></div>';
var outerHtml = $(html).wrap('<div />').parent().html();

hope this helps.

Martin Ackermann
  • 884
  • 6
  • 15