Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get html element as a string [duplicate]

Possible Duplicate:
jQuery, get html of a whole element

lets say I have:

<span>my span</span>

I would like have html as a string of this span

I use:

var mySpan = $('span');

what to do with the mySpan var to have as a result string "<span>my span</span>"

thanks for any help

like image 690
gruber Avatar asked Sep 27 '12 01:09

gruber


People also ask

How do I turn a HTML element into a string?

To convert a HTMLElement to a string with JavaScript, we can use the outerHTML property. const element = document. getElementById("new-element-1"); const elementHtml = element.

How do you clone an element in HTML?

The cloneNode() method creates a copy of a node, and returns the clone. The cloneNode() method clones all attributes and their values. Set the deep parameter to true if you also want to clone descendants (children).

How do you make a copy of an element?

You call the cloneNode() method on the element you want to copy. If you want to also copy elements nested inside it, pass in true as an argument. // Get the element var elem = document. querySelector('#elem1'); // Create a copy of it var clone = elem.


2 Answers

I think this will help: http://jsfiddle.net/HxU7B/2/.


UPDATE.

mySpan[0].outerHTML will take a previoulsy selected node and get a native outerHTML property. Since old Firefox versions doesn't have that property, we can use a bit of hack to get html - simply clone node to dummy div and then get this div's innerHTML: $('<div/>').append(mySpan.clone()).html()

like image 165
Igor Shastin Avatar answered Oct 09 '22 01:10

Igor Shastin


jQuery can't do that, but regular JavaScript DOM objects can:

var mySpanString = $('span').get(0).outerHTML;
like image 21
Joe Coder Avatar answered Oct 09 '22 02:10

Joe Coder