I know how to use .html() to grab the html inside of my selected element, like so:
<div id="outside>
<span>hello</span>
</div>
using something like
var span = $('#outside).html();
will grab my span as the html. My problem is when I have
<img id="image" src="image.png">
How can I assign the html, as a string, to a variable? Using
var image = $('#image').html()
gives me an empty string.
var image = $('#image')[0]
appears to get the html I want, but its actually still an object.
Answer: Use the concatenation operator (+) The simple and safest way to use the concatenation operator ( + ) to assign or store a bock of HTML code in a JavaScript variable.
The value of the id attribute for all elements are made available as properties of the global window object. Since window is the global object in the browser, it is accessible as a global variable.
In this article, we define a variable in the HTML by using the <var> tag in the document. It is a phrase tag and used to specify the variable in a mathematical equation or in the computer program. The content of this tag is displayed in an italic format in most of the browsers.
Try this:
var myAwesomeHTML = $('#image')[0].outerHTML
update:
$("<div></div>").append($("#image")).html()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With