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.

2
  • 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 ? Commented Dec 9, 2015 at 6:20
  • did you checked here? stackoverflow.com/questions/3754092/… Commented Dec 9, 2015 at 6:22

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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);
});

1 Comment

how can I append it to somewhere else? I got object using get(0);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.