Get html element as string

Possible duplicate:
jQuery get the html of the whole element

will say that I have:

<span>my span</span> 

I would like html as a string of this range

I use:

var mySpan = $('span');

what to do with mySpan var to result in the string "<span>my span</span>"

thanks for any help

+4
source share
3 answers

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


UPDATE

mySpan[0].outerHTML will take the previous selected node and get its own outerHTML property. Since older versions of Firefox do not have this property, we can use a bit of hacking to get html - just clone the node into a dummy div and then get that div innerHTML: $('<div/>').append(mySpan.clone()).html()

+7
source

jQuery cannot do this, but regular JavaScript DOM objects can:

 var mySpanString = $('span').get(0).outerHTML; 
+1
source

As others have stated, you can use outerHTML or a clone -> append -> html ()

But here is another way to do this,

 var nodeName = mySpan[0].nodeName.toLowerCase(); var outerHtml = "<"+nodeName +">"+mySpan.html()+"</"+nodeName +">"; 
+1
source

Source: https://habr.com/ru/post/1436501/


All Articles