Quantcast
Channel: convert HTML code to Javascript variable (string) - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Answer by Richard Peck for convert HTML code to Javascript variable (string)

$
0
0

If I'm right in assuming you want to generate "encoded" HTML through JS, this resource seems to answer the question:

function OuterHTML(element) {
  var container = document.createElement("div");
  container.appendChild(element.cloneNode(true));
  return container.innerHTML;
}

function encodeMyHtml(html) {
 encodedHtml = escape(html);
 encodedHtml = encodedHtml.replace(/\//g,"%2F");
 encodedHtml = encodedHtml.replace(/\?/g,"%3F");
 encodedHtml = encodedHtml.replace(/=/g,"%3D");
 encodedHtml = encodedHtml.replace(/&/g,"%26");
 encodedHtml = encodedHtml.replace(/@/g,"%40");
 return encodedHtml;
} 

So you'd be able to call (referencing this answer):

div = document.getElementById('jwplayer');
encoded = encodeMyHtml(div);

Here's a JSFiddle for you: http://jsfiddle.net/m8uyhz26/2/

If you want to return properly formatted HTML, use unescape with the returned data from encodeMyHtml


The main issue you have is lack of context in your question. If you gave people a reason why you need to convert HTML or JS etc, you'd be able to receive better answers.

As it stands, you'll get a bunch of JS hacks explaining how to turn HTML into JS-encoded strings etc.


Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>