1

When converting a string to an html object in JQuery, I'm not getting the entire segment and I was wondering if I'm using it properly.

Here is my code after populating 'data':

    console.log(data);
    console.log("---");
    console.log($(data).html());

Here are the results:

<div style='width:260px; height:128px; text-align:left' id='productTn'><img src='images/rProduct02.jpg' id='productTnImg' class='productTnImg' alt='Selected Product' style='border-style:none' height=128 width=128 /></div><div id='productLI' style='width:281px; min-height:185px'><b>Audi</b></div>
--- 
<img src="images/rProduct02.jpg" id="productTnImg" class="productTnImg" alt="Selected Product" style="border-style:none" height="128" width="128"> 

As you can see, after converting HTML to an object, and then that back to a string again, only the IMG portion is there, the rest is gone. Am I doing something wrong here?

Dave
  • 4,949
  • 6
  • 50
  • 73
  • possible duplicate of [Get selected element's outer HTML](http://stackoverflow.com/questions/2419749/get-selected-elements-outer-html) – Felix Kling Apr 11 '13 at 22:38

3 Answers3

1

$(data).html(); refer's to the innerHtml of data, This will return the img in your case.

with this $(data).html(); you are not converting your data into html, you are just asking jquery to return the html inside of your div

You asked - String to Object not working as expected

Your data variable is already an object

Read more about .html()

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
1

One prints the actual content of the variable data which is the whole string, while .html() retrieves the inner HTML of the div.

console.log(data); // prints the actual content of data
console.log($(data).html()); // prints the inner HTML of data
Nope
  • 22,147
  • 7
  • 47
  • 72
  • Doing something different just confused me for a second. Thanks. – Dave Apr 11 '13 at 22:45
  • @Dave: When you wrap `data` into a jQuery object, jQuery will treat the content in this case like any other reference to a DOM element wrapped in a jQuery object. Hence when calling `.html()` you get the HTML from inside the `div`. Calling `.html()` is the same as using `console.log($(data)[0].innerHTML);` which also just gives you the content of the `div`. – Nope Apr 11 '13 at 22:48
1

The jQuery .html() method will refer to the innerHTML of the matched element. If you want the outerHTML you could try something like this: console.log($(data).wrap("<div/>").parent().html()); though depending on what exactly you need, perhaps you're better off just referencing data itself? Wrapping the data node just to be able to select it could introduce other problems (CSS selectors, for instance).

ryanbrill
  • 1,981
  • 10
  • 13