0

As shown in this simple jsfiddle, the following code outputs the <p>I am inner content</p> but seems to drop the div tag. What am I missing?

var x = $('<div id="#testing"><p>I am inner content</p></div>');
alert(x.html());
Hamy
  • 20,662
  • 15
  • 74
  • 102
  • 1
    possible duplicate of [Get selected element's outer HTML](http://stackoverflow.com/questions/2419749/get-selected-elements-outer-html) – jpcanamaque Sep 29 '14 at 05:42

2 Answers2

3

Because .html() returns the innerHTML of x.

Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.

Youn eed to get the outerHTML

var log = (function() {
  var $log = $('#log');
  return function(msg) {
    $('<p/>', {
      text: msg
    }).prependTo($log)
  }
})();

var x = $('<div id="#testing"><p>I am inner content</p></div>');
log(x.prop('outerHTML'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="log"></div>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Oh, ok! Small followup question if you have time...why do I have to use `.prop` to get at the outer HTML? Is there a reason jquery seems to be encouraging programmers to use the innerHTML? I don't even see an official function .outerHTML – Hamy Sep 29 '14 at 05:43
  • PS - I'll accept this once stackoverflow allows me. I've timed out from too much use :-P – Hamy Sep 29 '14 at 05:44
  • @Hamy there is no jQuery utility method for getting outer html, it is a dom property([Element.outerHTML](https://developer.mozilla.org/en-US/docs/Web/API/Element.outerHTML))... [.prop()](http://api.jquery.com/prop/) is used to read dom element properties – Arun P Johny Sep 29 '14 at 05:46
1

Try this fiddle

var x = $('<div id="#testing"><p>I am inner content</p></div>');
alert(x.prop('outerHTML'));

outerHTML is similar to innerHTML, it is an element property that includes the opening an closing tags as well as the content.

Sameera Thilakasiri
  • 9,452
  • 10
  • 51
  • 86