Reputation: 5029
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?
Upvotes: 1
Views: 48
Reputation: 44740
$(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()
Upvotes: 1
Reputation: 2011
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).
Upvotes: 1
Reputation: 22329
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
Upvotes: 1