0
var x = '<div><span></span><div id="container"></div></div>'

console.log($(x).find('#container').html())

I wonder why this doesn't work, I just want to extract the html before it's append to somewhere.

Jennifer
  • 905
  • 9
  • 20
  • 4
    What do you mean it doesn't work, it returns an empty string for me, which is just as expected as `#container` doesn't contain any HTML at all ? – adeneo Dec 09 '15 at 06:20
  • did you checked here? http://stackoverflow.com/questions/3754092/how-to-get-an-html-element-from-a-string-with-jquery – gurvinder372 Dec 09 '15 at 06:22

2 Answers2

2

There is no html in #container. If you want to get the #container itself then you can do it with outerHTML like following.

var x = '<div><span></span><div id="container"></div></div>';
console.log($(x).find('#container')[0].outerHTML);
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
0

jQuery html api is for ( Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element. - http://api.jquery.com/html/)

your code is right, if you want to get "container" html, you have to call other function. e.g) get(0)

$(document).ready(function(){
  var x = '<div><span></span><div id="container"></div></div>';
  console.log($(x).find('#container').get(0));
});

if you want to add something or object, you can use append API.

$(document).ready(function(){
  var x = '<div><span></span><div id="container"></div></div>'; // string
  var $x = $(x); //$x is a jQuery object
  $x.find('#container').append($('<div>test</div>'));
  console.log($x);
});
Ray
  • 767
  • 4
  • 11