Get content inside script as text - javascript

I would like to print the content of a script tag is that possible with jquery?
index.html
<script type="text/javascript">
function sendRequest(uri, handler)
{
}
</script>
Code
alert($("script")[0].???);
result
function sendRequest(uri, handler)
{
}

Just give your script tag an id:
<div></div>
<script id='script' type='text/javascript'>
$('div').html($('#script').html());
</script>
​
http://jsfiddle.net/UBw44/

You can use native Javascript to do this!
This will print the content of the first script in the document:
alert(document.getElementsByTagName("script")[0].innerHTML);
This will print the content of the script that has the id => "myscript":
alert(document.getElementById("myscript").innerHTML);

Try this:
console.log(($("script")[0]).innerHTML);

You may use document.getElementsByTagName("script") to get an HTMLCollection with all scripts, then iterate it to obtain the text of each script. Obviously you can get text only for local javascript. For external script (src=) you must use an ajax call to get the text.
Using jQuery something like this:
var scripts=document.getElementsByTagName("script");
for(var i=0; i<scripts.length; i++){
script_text=scripts[i].text;
if(script_text.trim()!==""){ // local script text
// so something with script_text ...
}
else{ // external script get with src=...
$.when($.get(scripts[i].src))
.done(function(script_text) {
// so something with script_text ...
});
}
}

The proper way to get access to current script is document.scripts (which is array like HTMLCollection), the last element is always current script because they are processed and added to that list in order of parsing and executing.
var len = document.scripts.length;
console.log(document.scripts[len - 1].innerHTML);
The only caveat is that you can't use any setTimeout or event handler that will delay the code execution (because next script in html can be parsed and added when your code will execute).
EDIT: Right now the proper way is to use document.currentScript. The only reason not to use this solution is IE. If you're force to support this browser use original solution.

Printing internal script:
var isIE = !document.currentScript;
function renderPRE( script, codeScriptName ){
if (isIE) return;
var jsCode = script.innerHTML.trim();
// escape angled brackets between two _ESCAPE_START_ and _ESCAPE_END_ comments
let textsToEscape = jsCode.match(new RegExp("// _ESCAPE_START_([^]*?)// _ESCAPE_END_", 'mg'));
if (textsToEscape) {
textsToEscape.forEach(textToEscape => {
jsCode = jsCode.replace(textToEscape, textToEscape.replace(/</g, "&lt")
.replace(/>/g, "&gt")
.replace("// _ESCAPE_START_", "")
.replace("// _ESCAPE_END_", "")
.trim());
});
}
script.insertAdjacentHTML('afterend', "<pre class='language-js'><code>" + jsCode + "</code></pre>");
}
<script>
// print this script:
let localScript = document.currentScript;
setTimeout(function(){
renderPRE(localScript)
}, 1000);
</script>
Printing external script using XHR (AJAX):
var src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js";
// Exmaple from:
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
function reqListener(){
console.log( this.responseText );
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", src);
oReq.send();
*DEPRECATED*: Without XHR (AKA Ajax)
If you want to print the contents of an external script (file must reside on the same domain), then it's possible to use a <link> tag with the rel="import" attribute and then place the script's source in the href attribute. Here's a working example for this site:
<!DOCTYPE html>
<html lang="en">
<head>
...
<link rel="import" href="autobiographical-number.js">
...
</head>
<body>
<script>
var importedScriptElm = document.querySelector('link[rel="import"]'),
scriptText = scriptText.import.body.innerHTML;
document.currentScript.insertAdjacentHTML('afterend', "<pre>" + scriptText + "</pre>");
</script>
</body>
</html>
This is still experimental technology, part of web-components. read more on MDN

Related

Alternate / Equivalent of jQuery.load in pure JavaScript? [duplicate]

I want home.html to load in <div id="content">.
<div id="topBar"> HOME </div>
<div id ="content"> </div>
<script>
function load_home(){
document.getElementById("content").innerHTML='<object type="type/html" data="home.html" ></object>';
}
</script>
This works fine when I use Firefox. When I use Google Chrome, it asks for plug-in. How do I get it working in Google Chrome?
I finally found the answer to my problem. The solution is
function load_home() {
document.getElementById("content").innerHTML='<object type="text/html" data="home.html" ></object>';
}
Fetch API
function load_home (e) {
(e || window.event).preventDefault();
fetch("http://www.yoursite.com/home.html" /*, options */)
.then((response) => response.text())
.then((html) => {
document.getElementById("content").innerHTML = html;
})
.catch((error) => {
console.warn(error);
});
}
XHR API
function load_home (e) {
(e || window.event).preventDefault();
var con = document.getElementById('content')
, xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (e) {
if (xhr.readyState == 4 && xhr.status == 200) {
con.innerHTML = xhr.responseText;
}
}
xhr.open("GET", "http://www.yoursite.com/home.html", true);
xhr.setRequestHeader('Content-type', 'text/html');
xhr.send();
}
based on your constraints you should use ajax and make sure that your javascript is loaded before the markup that calls the load_home() function
Reference - davidwalsh
MDN - Using Fetch
JSFIDDLE demo
You can use the jQuery load function:
<div id="topBar">
HOME
</div>
<div id ="content">
</div>
<script>
$(document).ready( function() {
$("#load_home").on("click", function() {
$("#content").load("content.html");
});
});
</script>
Sorry. Edited for the on click instead of on load.
Fetching HTML the modern Javascript way
This approach makes use of modern Javascript features like async/await and the fetch API. It downloads HTML as text and then feeds it to the innerHTML of your container element.
/**
* #param {String} url - address for the HTML to fetch
* #return {String} the resulting HTML string fragment
*/
async function fetchHtmlAsText(url) {
return await (await fetch(url)).text();
}
// this is your `load_home() function`
async function loadHome() {
const contentDiv = document.getElementById("content");
contentDiv.innerHTML = await fetchHtmlAsText("home.html");
}
The await (await fetch(url)).text() may seem a bit tricky, but it's easy to explain. It has two asynchronous steps and you could rewrite that function like this:
async function fetchHtmlAsText(url) {
const response = await fetch(url);
return await response.text();
}
See the fetch API documentation for more details.
I saw this and thought it looked quite nice so I ran some tests on it.
It may seem like a clean approach, but in terms of performance it is lagging by 50% compared by the time it took to load a page with jQuery load function or using the vanilla javascript approach of XMLHttpRequest which were roughly similar to each other.
I imagine this is because under the hood it gets the page in the exact same fashion but it also has to deal with constructing a whole new HTMLElement object as well.
In summary I suggest using jQuery. The syntax is about as easy to use as it can be and it has a nicely structured call back for you to use. It is also relatively fast. The vanilla approach may be faster by an unnoticeable few milliseconds, but the syntax is confusing. I would only use this in an environment where I didn't have access to jQuery.
Here is the code I used to test - it is fairly rudimentary but the times came back very consistent across multiple tries so I would say precise to around +- 5ms in each case. Tests were run in Chrome from my own home server:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="content"></div>
<script>
/**
* Test harness to find out the best method for dynamically loading a
* html page into your app.
*/
var test_times = {};
var test_page = 'testpage.htm';
var content_div = document.getElementById('content');
// TEST 1 = use jQuery to load in testpage.htm and time it.
/*
function test_()
{
var start = new Date().getTime();
$(content_div).load(test_page, function() {
alert(new Date().getTime() - start);
});
}
// 1044
*/
// TEST 2 = use <object> to load in testpage.htm and time it.
/*
function test_()
{
start = new Date().getTime();
content_div.innerHTML = '<object type="text/html" data="' + test_page +
'" onload="alert(new Date().getTime() - start)"></object>'
}
//1579
*/
// TEST 3 = use httpObject to load in testpage.htm and time it.
function test_()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
content_div.innerHTML = xmlHttp.responseText;
alert(new Date().getTime() - start);
}
};
start = new Date().getTime();
xmlHttp.open("GET", test_page, true); // true for asynchronous
xmlHttp.send(null);
// 1039
}
// Main - run tests
test_();
</script>
</body>
</html>
try
async function load_home(){
content.innerHTML = await (await fetch('home.html')).text();
}
async function load_home() {
let url = 'https://kamil-kielczewski.github.io/fractals/mandelbulb.html'
content.innerHTML = await (await fetch(url)).text();
}
<div id="topBar"> HOME </div>
<div id="content"> </div>
When using
$("#content").load("content.html");
Then remember that you can not "debug" in chrome locally, because XMLHttpRequest cannot load -- This does NOT mean that it does not work, it just means that you need to test your code on same domain aka. your server
You can use the jQuery :
$("#topBar").on("click",function(){
$("#content").load("content.html");
});
$("button").click(function() {
$("#target_div").load("requesting_page_url.html");
});
or
document.getElementById("target_div").innerHTML='<object type="text/html" data="requesting_page_url.html"></object>';
<script>
var insertHtml = function (selector, argHtml) {
$(document).ready(function(){
$(selector).load(argHtml);
});
var targetElem = document.querySelector(selector);
targetElem.innerHTML = html;
};
var sliderHtml="snippets/slider.html";//url of slider html
var items="snippets/menuItems.html";
insertHtml("#main",sliderHtml);
insertHtml("#main2",items);
</script>
this one worked for me when I tried to add a snippet of HTML to my main.html.
Please don't forget to add ajax in your code
pass class or id as a selector and the link to the HTML snippet as argHtml
There is this plugin on github that load content into an element. Here is the repo
https://github.com/abdi0987/ViaJS
load html form a remote page ( where we have CORS access )
parse the result-html for a specific portion of the page
insert that part of the page in a div on current-page
//load page via jquery-ajax
$.ajax({
url: "https://stackoverflow.com/questions/17636528/how-do-i-load-an-html-page-in-a-div-using-javascript",
context: document.body
}).done(function(data) {
//the previous request fails beceaus we dont have CORS on this url.... just for illlustration...
//get a list of DOM-Nodes
var dom_nodes = $($.parseHTML(data));
//find the question-header
var content = dom_nodes.find('#question-header');
//create a new div and set the question-header as it's content
var newEl = document.createElement("div");
$(newEl).html(content.html());
//on our page, insert it in div with id 'inserthere'
$("[id$='inserthere']").append(newEl);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>part-result from other page:</p>
<div id="inserthere"></div>
Use this simple code
<div w3-include-HTML="content.html"></div>
<script>w3.includeHTML();</script>
</body>```
This is usually needed when you want to include header.php or whatever page.
In Javascript it's easy especially if you have HTML page and don't want to use php include function but at all you should write php function and add it as Javascript function in script tag.
In this case you should write it without function followed by name Just. Script rage the function word and start the include header.php
i.e convert the php include function to Javascript function in script tag and place all your content in that included file.
I use jquery, I found it easier
$(function() {
$("#navigation").load("navbar.html");
});
in a separate file and then load javascript file on html page
showhide.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showHide(switchTextDiv, showHideDiv)
{
var std = document.getElementById(switchTextDiv);
var shd = document.getElementById(showHideDiv);
if (shd.style.display == "block")
{
shd.style.display = "none";
std.innerHTML = "<span style=\"display: block; background-color: yellow\">Show</span>";
}
else
{
if (shd.innerHTML.length <= 0)
{
shd.innerHTML = "<object width=\"100%\" height=\"100%\" type=\"text/html\" data=\"showhide_embedded.html\"></object>";
}
shd.style.display = "block";
std.innerHTML = "<span style=\"display: block; background-color: yellow\">Hide</span>";
}
}
</script>
</head>
<body>
<a id="switchTextDiv1" href="javascript:showHide('switchTextDiv1', 'showHideDiv1')">
<span style="display: block; background-color: yellow">Show</span>
</a>
<div id="showHideDiv1" style="display: none; width: 100%; height: 300px"></div>
</body>
</html>
showhide_embedded.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function load()
{
var ts = document.getElementById("theString");
ts.scrollIntoView(true);
}
</script>
</head>
<body onload="load()">
<pre>
some text 1
some text 2
some text 3
some text 4
some text 5
<span id="theString" style="background-color: yellow">some text 6 highlight</span>
some text 7
some text 8
some text 9
</pre>
</body>
</html>
If your html file resides locally then go for iframe instead of the tag. tags do not work cross-browser, and are mostly used for Flash
For ex : <iframe src="home.html" width="100" height="100"/>

JavaScript function only works after page reload

I know this has been asked a lot on here, but all the answers work only with jQuery and I need a solution without it.
So after I do something, my Servlet leads me to a JSP page. My JS function should populate a drop down list when the page is loaded. It only works properly when the page is refreshed tho.
As I understand this is happening because I want to populate, using innerHTML and the JS function gets called faster then my HTML page.
I also get this error in my Browser:
Uncaught TypeError: Cannot read property 'innerHTML' of null
at XMLHttpRequest.xmlHttpRequest.onreadystatechange
I had a soulution for debugging but I can't leave it in there. What I did was, every time I opened that page I automatically refreshed the whole page. But my browser asked me every time if I wanted to do this. So that is not a solution that's pretty to say the least.
Is there something I could do to prevent this?
Edit:
document.addEventListener("DOMContentLoaded", pupulateDropDown);
function pupulateDropDown() {
var servletURL = "./KategorienHolen"
let xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.onreadystatechange = function () {
if (xmlHttpRequest.readyState === 4 && xmlHttpRequest.status === 200) {
console.log(xmlHttpRequest.responseText);
let katGetter = JSON.parse(xmlHttpRequest.responseText);
JSON.stringify(katGetter);
var i;
for(i = 0; i <= katGetter.length -1; i++){
console.log(katGetter[i].id);
console.log(katGetter[i].kategorie);
console.log(katGetter[i].oberkategorie);
if (katGetter[i].oberkategorie === "B") {
document.getElementById("BKat").innerHTML += "" + katGetter[i].kategorie + "</br>";
} else if (katGetter[i].oberkategorie === "S") {
document.getElementById("SKat").innerHTML += "" + katGetter[i].kategorie + "</br>";
} else if (katGetter[i].oberkategorie ==="A") {
document.getElementById("ACat").innerHTML += "" + katGetter[i].kategorie + "</br>";
}
// document.getElementsByClassName("innerDiv").innerHTML = "" + katGetter.kategorie + "";
// document.getElementById("test123").innerHTML = "" + katGetter.kategorie + "";
}
}
};
xmlHttpRequest.open("GET", servletURL, true);
xmlHttpRequest.send();
}
It can depend on how + when you're executing the code.
<html>
<head>
<title>In Head Not Working</title>
<!-- WILL NOT WORK -->
<!--<script>
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
</script>-->
</head>
<body>
<p>Replace This</p>
<!-- Will work because the page has finished loading and this is the last thing to load on the page so it can find other elements -->
<script>
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
</script>
</body>
</html>
Additionally you could add an Event handler so when the window is fully loaded, you can then find the DOM element.
<html>
<head>
<title>In Head Working</title>
<script>
window.addEventListener('load', function () {
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
});
</script>
</head>
<body>
<p>Replace This</p>
</body>
</html>
Define your function and add an onload event to body:
<body onload="pupulateDropDown()">
<!-- ... -->
</body>
Script needs to be loaded again, I tried many options but <iframe/> works better in my case. You may try to npm import for library related to your script or you can use the following code.
<iframe
srcDoc={`
<!doctype html>
<html>
<head>
<style>[Style (If you want to)]</style>
</head>
<body>
<div>
[Your data]
<script type="text/javascript" src="[Script source]"></script>
</div>
</body>
</html>
`}
/>
Inside srcDoc, it's similar to normal HTML code.
You can load data by using ${[Your Data]} inside srcDoc.
It should work :
document.addEventListener("DOMContentLoaded", function(){
//....
});
You should be using the DOMContentLoaded event to run your code only when the document has been completely loaded and all elements have been parsed.
window.addEventListener("DOMContentLoaded", function(){
//your code here
});
Alternatively, place your script tag right before the ending body tag.
<body>
<!--body content...-->
<script>
//your code here
</script>
</body>

RSS giving me unclosed tag link, couldn't get the innerHTML

I'm doing a study using a RSS, but the Web Site gives me a RSS with an unclosed tag then I couldn't get the innerHTML of this tag.
I don't know how to resolve the problem with jquery and make the tag closed or a possible solution like this.
Here is the code :
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" content="xml">
<script type="text/javascript" src="api/jquery.js"></script>
</head>
<body>
<p id="someElement" visibility="hidden"></p>
<p id="anotherElement"></p>
<script type="text/javascript">
var x = new XMLHttpRequest();
x.open("GET", "http://www.lemonde.fr/rss/une.xml", true);
x.onreadystatechange = function () {
if (x.readyState == 4 && x.status == 200)
{
var doc = x.responseXML;
var string = (new XMLSerializer()).serializeToString(doc);
$("#someElement").append(string);
alert("test");
var tag = document.getElementsByTagName("item");
for(var i = 0, max = tag.length; i < max; i++){
var htmli = tag[i];
//alert(htmli.innerHTML);
//uncomment the alert to see the xml got from the rss
var title = htmli.getElementsByTagName("title")[0].innerHTML;
var link = htmli.getElementsByTagName("link")[0].innerHTML;
var description = htmli.getElementsByTagName("description")[0].innerHTML;
var toAdd = "<ul><li> title : " +title+"</li><li> link : "+ link +" </li><li> description :"+description+" </li></ul>";
$("#anotherElement").append(toAdd);
}
}
};
x.send(null);
</script>
</body>
</html>
Any solution to this?
I have jquery in a folder named api.
Thanks a lot !!
(I notice that while you include jQuery in a script tag, you're not actually using it in your code. It's much better practice to use jQuery's functionality to manage AJAX requests and serialization, if you're going to use it at all, as they cover many more situations and browser versions. I'd also recommend retrieving jQuery from a CDN rather than hosting it yourself. jQuery has had the ability to parse XML natively since 1.5. The following was written using 1.12.)
I ran into the same issue with unclosed tags in an RSS feed and came up with a terrible solution to it. I have not tested this cross-browser and would not recommend incorporating it into production code, but it worked to solve a one-time problem for me.
The idea is to take the raw output of the RSS item's text, cram it into the jQuery HTML parser, and then manually inspect its output until we get to an item that it thinks might have been an HTML <link> tag. Because we know the RSS link tag isn't closed, the next thing it encounters should be parsed as an HTML Text object, which we can extract for our permalink URL.
Here's how I would rewrite your script to take better advantage of jQuery and incorporate my hack. (I'm assuming you have set up CORS or something else so that you can actually retrieve the feed from lemonde.fr cross-domain.)
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" content="xml">
<script type="text/javascript" src="//code.jquery.com/jquery-1.12.4.min.js"></script>
</head>
<body>
<p id="someElement" visibility="hidden"></p>
<p id="anotherElement"></p>
<script type="text/javascript">
(function($, window, document) {
function fetchFeed(url) {
// use jQuery to handle AJAX
$.get(url, function(data) {
// parse XML result with jQuery
var $XML = $(data);
$XML.find("item").each(function() {
// ensure that we have a jQuery-wrapped _this_ object and
// create a new object with the properties we want
var $this = $(this),
item = {
title: $this.find("title").text(),
description: $this.find("description").text(),
link: ""
};
// since the XML parser will treat the unclosed <link> as valid,
// we instead send the raw output to the HTML parser and tell it do to its best
var $redigested = $($this.html());
// jQuery should produce an array of HTML DOM objects
for (var i = 0; i < $redigested.length; i++) {
// if we found an HTMLLinkElement--a <link> tag--followed by a Text element, that's our URL
if ($redigested[i] instanceof HTMLLinkElement && $redigested.length >= i + 1 && $redigested[i + 1] instanceof Text) {
item.link = $redigested[i + 1].data;
break;
}
}
console.log("link: " + item.link);
var toAdd = "<ul><li> title: " + item.title + "</li><li> link: " + item.link + " </li><li> description: " + item.description + " </li></ul>";
$("#anotherElement").append(toAdd);
});
});
}
$(function() {
// call the fetch function on DOM ready
fetchFeed("http://www.lemonde.fr/rss/une.xml");
});
})(jQuery, window, document);
</script>
</body>
</html>

How to remove <script> tags from an HTML page using C#?

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
if (window.self === window.top) { $.getScript("Wing.js"); }
</script>
</head>
</html>
Is there a way in C# to modify the above HTML file and convert it into this format:
<html>
<head>
</head>
</html>
Basically my goal is to remove all the JavaScript from the HTML page. I don't know what is be the best way to modify the HTML files. I want to do it programmatically as there are hundreds of files which need to be modified.
It can be done using regex:
Regex rRemScript = new Regex(#"<script[^>]*>[\s\S]*?</script>");
output = rRemScript.Replace(input, "");
May be worth a look: HTML Agility Pack
Edit: specific working code
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
string sampleHtml =
"<html>" +
"<head>" +
"<script type=\"text/javascript\" src=\"jquery.js\"></script>" +
"<script type=\"text/javascript\">" +
"if (window.self === window.top) { $.getScript(\"Wing.js\"); }" +
"</script>" +
"</head>" +
"</html>";
MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(sampleHtml));
doc.Load(ms);
List<HtmlNode> nodes = new List<HtmlNode>(doc.DocumentNode.Descendants("head"));
int childNodeCount = nodes[0].ChildNodes.Count;
for (int i = 0; i < childNodeCount; i++)
nodes[0].ChildNodes.Remove(0);
Console.WriteLine(doc.DocumentNode.OuterHtml);
I think as others have said, HtmlAgility pack is the best route. I've used this to scrape and remove loads of hard to corner cases. However, if a simple regex is your goal, then maybe you could try <script(.+?)*</script>. This will remove nasty nested javascript as well as normal stuff, i.e the type referred to in the link (Regular Expression for Extracting Script Tags):
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
if (window.self === window.top) { $.getScript("Wing.js"); }
</script>
<script> // nested horror
var s = "<script></script>";
</script>
</head>
</html>
usage:
Regex regxScriptRemoval = new Regex(#"<script(.+?)*</script>");
var newHtml = regxScriptRemoval.Replace(oldHtml, "");
return newHtml; // etc etc
This may seem like a strange solution.
If you don't want to use any third party library to do it and don't need to actually remove the script code, just kind of disable it, you could do this:
html = Regex.Replace(html , #"<script[^>]*>", "<!--");
html = Regex.Replace(html , #"<\/script>", "-->");
This creates an HTML comment out of script tags.
using regex:
string result = Regex.Replace(
input,
#"</?(?i:script|embed|object|frameset|frame|iframe|meta|link|style)(.|\n|\s)*?>",
string.Empty,
RegexOptions.Singleline | RegexOptions.IgnoreCase
);

how to insert javascript code via jquery?

<div id="example">
</div>
<script type="text/javascript">
function insert() {
var data = '<script type="text/javascript"> function test() { a = 5; }<\/script>';
$("#example").append(data);
}
function get() {
var content = $("#example").html();
alert(content);
}
</script>
INSERT
GET
</body>
</html>
what i want to do:
when i click on insert, i want to insert this code into example div:
<script type="text/javascript"> function test() { a = 5; }<\/script>
when i click on get, i want to get that code, which i inserted there.
but when i click on insert, and then on get, there's no code.. where is problem ? thanks
According to your comment to Adam Bellaire, you want the script tag to display as normal text. What you are looking to do is encode the text with HTML entities, this will prevent the browser from processing it as normal HTML.
var enc = $('<div/>').text('<script type="text/javascript"> function test() { a = 5; }<\/script>').html();
$("#example").append(enc);
This works:
function insert() {
var data = '<script type="text/javascript"> function test() { a = 5; }<\/script>';
$('#example').text(data);
}
function get() {
var content = $('#example').text();
alert(content);
}
Are you checking for the code by browsing the live version of the DOM, using a tool like Firebug? If you are expecting to see your code rendered in your regular browser window, you won't, because the script tags are actually parsed when they are inserted, and script tags aren't visible elements in an HTML page.

Categories