0

Hello everyone,

I'm a little bit confused here, trying to store couple of html elements into a variable. But when I try to print out the content of my variable, some elements are not being displayed. is that some kind of magic :) or what I'm doing wrong exactly?

This is then causing issues in my other functions, which are trying to find certain elements in the variable.

var template = $(" <div class='item'><span id='item_stats_info'> <div id='item_name'> </div> </span> </div>");

console.log(template.html());

Result:

<span id="item_stats_info"> <div id="item_name"> </div> </span> 

Could you guys advise me on what's the best way to store html elements in a variable?

Thansk in advance, Alex

Wracker
  • 589
  • 10
  • 32
  • 2
    You're storing a single element in `template`. It happens to have some descendants. `.html()` returns an element's **inner** HTML (specifically, the single element originally stored in `template`...which is a span with a div inside of it) – Ian Jul 01 '14 at 14:22
  • Store the template as plain text, not a jquery object containing elements. – Kevin B Jul 01 '14 at 14:24
  • The console output is correct in your case because it is showing the inner html of the element you have created. If you explain us what you are you trying to achieve, someone can tell you what to do. – Abhishek Jain Jul 01 '14 at 14:27

2 Answers2

1

The .html() method of jQuery returns the HTML inside of the element, since you need to get the outer HTML, you can try wrapping it in another div:

var template = $("<div> <div class='item'><span id='item_stats_info'> <div id='item_name'> </div> </span> </div> </div>");

console.log(template.html());
reaxis
  • 1,361
  • 12
  • 11
  • it looks like you're right. So it must be something wrong in my functions that they can't find the "item" class in the variable. – Wracker Jul 01 '14 at 14:26
  • 1
    There's nothing wrong in your code, it's just that you're asking for the inner HTML, which doesn't give you back the outer div itself. – Trent Jul 01 '14 at 14:29
1

Use this to get the full html, not the inner html....

console.log(template.prop('outerHTML'));
Trent
  • 1,280
  • 11
  • 12