Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting HTML element to string in JavaScript / JQuery

I would like to convert a html element created from a string back to the string after some modifications. But I get an empty string instead.

$('<iframe width="854" height="480" src="http://www.youtube.com/embed/gYKqrjq5IjU?feature=oembed" frameborder="0" allowfullscreen></iframe>').html();

How can I do that another way?

like image 755
ciembor Avatar asked Nov 06 '13 12:11

ciembor


People also ask

How to convert HTML tag to string in jQuery?

var BillHtml = $('#up'). html();

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.

What is parseHTML in JavaScript?

parseHTML uses native methods to convert the string to a set of DOM nodes, which can then be inserted into the document. These methods do render all trailing or leading text (even if that's just whitespace).

How to convert string to text in jQuery?

To convert, use JavaScript parseInt() function which parses a string and returns an integer. var sVal = '234'; var iNum = parseInt(sVal); //Output will be 234.


3 Answers

You can do this:

var $html = $('<iframe width="854" height="480" src="http://www.youtube.com/embed/gYKqrjq5IjU?feature=oembed" frameborder="0" allowfullscreen></iframe>');    
var str = $html.prop('outerHTML');
console.log(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

FIDDLE DEMO

like image 200
palaѕн Avatar answered Oct 19 '22 16:10

palaѕн


What you want is the outer HTML, not the inner HTML :

$('<some element/>')[0].outerHTML;
like image 34
Denys Séguret Avatar answered Oct 19 '22 16:10

Denys Séguret


(document.body.outerHTML).constructor will return String. (take off .constructor and that's your string)

That aughta do it :)

like image 2
Cody Avatar answered Oct 19 '22 17:10

Cody