Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to save an element's html to a variable

Tags:

html

jquery

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.

like image 362
user883036 Avatar asked Nov 04 '11 18:11

user883036


People also ask

How do you save the content of an HTML element to a variable?

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.

Can HTML Id be a 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.

How do you assign a variable in HTML?

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.


1 Answers

Try this:

var myAwesomeHTML = $('#image')[0].outerHTML

update:

$("<div></div>").append($("#image")).html()
like image 119
Keith.Abramo Avatar answered Nov 06 '22 11:11

Keith.Abramo