Lets say I have a string called Test, and its value is:
<img src=test.gif></img>
<p> Testing 123 </p>
Is it somehow possible to use it as code since the HTML isn't compiled?
Edit: I tried this and it didn't work.
<body>
<p id="myText" onload="HTMLThing()"> Soon. </p>
</body>
<script>
var testString = "<img src=test.gif></img><p> Testing 123 </p>"
function HTMLThing(){
document.getElementById("myText").innerHTML=testString;
}
</script>
I don't know which language you are using, but certainly you can open a file(with .html extension) and dump the string to that file. Later, when you open the HTML file, you will get the rendered web page.
But be sure about the directory in which you create that file, should also contain the image, or you can change the image's location in the string.
On your page you can create HTML element and give it some ID, e.g. "myText". E.g.:
<div id="myText">This is what's shown before Javascript runs.</div>
Then in your Javascript code you can do:
document.getElementById("myText").innerHTML='<img src=test.gif></img><p> Testing 123 </p>';
That will fill your element with the above code with the obvious consequences (adding image and text) if that's what you want.
Update: If you're calling your Javascript function with the onload event, be sure to put onload="myFunction()" assignment into the body tag, since it doesn't work in div, p and so on. Alternatively, you can use onClick instead of onload which will work with div, p and other elements.
The code below should work. The problem was that the <p> element does not fire the onload event, but the body does.
<body onload="HTMLThing()">
<p id="myText">Soon.</p>
<script type="text/javascript">
var testString = "<img src=test.gif></img><p> Testing 123 </p>";
function HTMLThing(){
document.getElementById("myText").innerHTML = testString;
}
</script>
</body>
There are several ways to do the onload event, another method:
<body>
<p id="myText">Soon.</p>
<script type="text/javascript">
var testString = "<img src=test.gif></img><p> Testing 123 </p>";
function HTMLThing(){
document.getElementById("myText").innerHTML = testString;
}
window.onload = function(){
HTMLThing();
}
</script>
</body>
Related
What I want to do is allow the user to input a string then display that string in the web page inside a div element, but I don't want the user to be able to add a bold tag or anything that would actually make the HTML text bold. How could I make it so the text entered by the user does not get converted into HTML code, if the text has an HTML tag in it?
Use createTextNode(value) and append it to your element(Standard solution) or innerText(Non standard solution) instead of innerHTML.
For a JQuery solution look at Dan Weber's answer.
here's a neat little function to sanitize untrusted text:
function sanitize(ht){ // tested in ff, ch, ie9+
return new Option(ht).innerHTML;
}
example input/output:
sanitize(" Hello <img src=data:image/png, onmouseover=alert(666) onerror=alert(666)> World");
// == " Hello <img src=data:image/png, onmouseover=alert(666) onerror=alert(666)> World"
It will achieve the same results as setting elm.textContent=str;, but as a function, you can use it easier inline, like to run markdown after you sanitize() so that you can pretty-format input (eg. linking URLs) without running arbitrary HTML from the user.
use .text() when setting the text in the div rather than .HTML. This will render it as text instead of html.
$(document).ready(function() {
// Handler for .ready() called.
$("#change-it").click(function() {
var userLink = $('#usr-input').val().replace(/.*?:\/\//g, "");
$('#users-text').text(userLink);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="form-control" id="usr-input">
<br>
<button id="change-it" type="button">Update Text</button>
<br>
<div id="users-text"></div>
Why not simply use .text() ?
$('#in').on('keyup', function(e) {
$('#out').text($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="in">
<br>
<div id="out"></div>
What I ultimately want is to retrieve the innerHTML of the example script below (the html is to be put in a database). It must include the onclick events also. However in the generated HTML there is no onclick event available.
<html>
</head>
<script>
function test() {
this.goodbye="goodbye!";
this.elem=document.createElement('div');
this.elem.style.border='1px solid #888888';
this.elem.textContent="hello";
this.elem.style.cursor='pointer';
var that=this;
this.elem.onclick=function(){that.say_goodbye();}
document.getElementsByTagName('body')[0].appendChild(this.elem);
}
test.prototype.say_goodbye=function(blockid) {
this.elem.textContent=this.goodbye;
}
</script>
</head>
<body>
<script>var obj = new test();</script>
get html
</body>
</html>
the line of importance is thus:
this.elem.onclick=function(){that.say_goodbye();}
I tried to add it as attribute like:
this.elem.setAttribute('onclick',that.say_goodbye.bind(that));
But is doesn't work. When I click the link in the given code the browser alerts:
<div> onclick="function(){[native code]}" ..... </div>
In this case the HTML now has an 'onclick' event but contains '[native code]' as action.
Anyone an idea on how to make the code work?
The reason you get this is that attribute value is text always and you are trying to put object into it (functions are objects). This case you should rather use this.elem = that.say_goodbye.bind(that).
I would like to call the following javaScript function so it gets outputted to a HTML P tag, but am not sure how to do this without explicitly calling the function in the HTML file.
I do not want to do this...
<p class="showcode">
<script type="text/javascript">
wise_words();
</script>
</p>
I would like to keep the javaScript code all in one js file.
I have tried it this way but this does not seem to work...
document.getElementById("showcode").innerHTML = wise_words();
I would really appreciate any help as to what I am doing wrong.
Here is my code... http://codepen.io/anon/pen/qfLdE I would like to have the generated text get outputted inside the grey box.
You should call the function in an onload handler, so that it is executed after the DOM has been constructed:
window.onload = function() {
document.getElementById("showcode").innerHTML = wise_words();
}
Another problem is that your wise_words() function is using document.write (please don't use document.write) instead of returning a value. You need to return a value:
var retText = wiseText[nextVal][0];
nextVal += 1;
writeCookie("wisewords", nextVal.toString(), 33);
return retText;
Try following using Jquery:
$(".showcode").html(wise_words());
NOTE: Assuming your function returns the HTML/text.
<p class="showcode">
<script type="text/javascript">
document.write(wise_words());
</script>
</p>
or:
<body onload="document.getElementById('showcode').innerHTML = wise_words()">
<p id="showcode">
</p>
</body>
(note id instead of class).
So I have a function that writes a string into a div.
The string is declared as content, which consists of html code, like this:
<h2>This is a test result</h2>
<script type="text/javascript" src="example_content.js"></script>
<script type="text/javascript"> document.write(example_content); </script>
where example_content.js :
example_content = '<p>some text some text some text some text some text</p>'
+ '<p>some more text....</p>'
+ '<hr />'
+ '<p>End of text</p>';
Problem is, instead of getting this in the div:
<h2>This is a test result</h2>
<p>some text some text some text some text some text</p>
<p>some more text....</p>
<hr />
<p>End of Text</p>
I end up, literaly, with this:
<h2>This is a test result/h2>
<script type="text/javascript" src="example_content.js"></script>
<script type="text/javascript"> document.write(example_content); </script>
Is there a way to avoid writting the script tag as a string ? but as an actual script ?
Thanks for any help in advance :)
You can't do that. You can't add script tags and execute them by writing the HTML. If you must load scripts dynamically, you should add them to the DOM. You can try this to load an external script file and execute the method.
(function(document){
var s = document.createElement('script');
s.id = "external_content";
s.async = true;
s.src = "example_content.js";
document.getElementsByTagName('head')[0].appendChild(s);
s.onload = function() {
document.write(example_content);
}
}(document));
What it basically does is that it creates a new script element dynamically and adds it to the DOM. It also sets an onload event handler which would fire once the script is downloaded completely.
I'm not sure about this question due to the wording however you don't need two <script> tags. At the end of the example_content.js place the document.write(example_content); then remove the <script type="text/javascript"> document.write(example_content); </script> from the html file.
Also if this is what you want I would recommend you use object.innerHTML rather than document.write and place the script at the bottom of your page.
if this doesn't work or isn't what you want please put a comment and I'll remove and use JSLint for an example.
Here's some info: https://developer.mozilla.org/en-US/docs/DOM/element.innerHTML
Okay so basically you want to write HTML inside the contents of your div. Say you have a div with the following id: myContentDiv
/**
* NOTICE HOW IM USING \ before " TO ESCAPE THE CHARACTERS INSIDE THE HTML STRING
*/
var yourCustomHTMLString = "<h1>this is a tag</h1><div class=\"yourClass\">something</div>";
var contentDiv = document.getElementById('myContentDiv');
contentDiv.innerHTML = yourCustomHTMLString;
Also, in your mark-up you need to specify a trigger for your JS, for instance an onload trigger.
window.onload = function(){
document.write(example_content);
}
And now say you want a function that will load an HTML string into a div.
function loadContent(HTMLstring, targetDivID)
{
var myDiv = document.getElementById(targetDivID);
myDiv.innerHTML = HTMLstring;
}
If you are trying to include a JS script inside another JS script, you need Ajax. If you are using a JS library, all common ones have a script load method predefined.
Dynamically load a JavaScript file
If I understand you correctly, you insert your content as innerHTML into a <div> , and the scripts don't execute.
As far as I know, this is the expected behavior, as there is no onLoad, document.ready etc. event when you alter the innerHTML of an element.
You could parse the inserted string for <script> nodes. Warning, this is a very "hacky" thing to do, usually there are better ways, for example using the success callback of the ajax functions of the various script libraries.
Nevertheless, here is what we used once. This needs to be executed after you inserted your content string. Please don't judge me, I was young and the time was short...
var div = document.getElementById("yourParentDiv");
if(div != null){
var x = div.getElementsByTagName("script");
for(var i=0;i<x.length;i++) {
eval(x[i].text);
}
}
I wrote an ajax program.when i am getting response, at that time i will display
that content in my web page using html tags.
So how can I use html tags in javascript?
A sample data you get from server, and a sample html you want to add would make it easier for people to help you.
The basic steps are
1.Get a reference to the html node you want to put the new data in. There are multiple strategies to get reference to the node. If it has an id, it's most starightforward.
2.set innerHTML property.
eg
var node = document.getElementById("targetNode");
node.innerHTML = "<div>data</div>";
Well... Not much detail so not much of an answer...
Easy way
document.write("<body> <div> this is on my page! </div> </body>
or you can edit the innerhtml of an element to place things inside it
document.getElementById("id").innerHTML = "<div>This is inside my element with id="id" </div>"
Answers the question, no?
Instead of embedding html into javascript, you could make a bunch of predefined javascript functions and then use them outside of the script tags. For example, here's how to display a picture while still using the javascript functions.
<html>
<script type="text/javascript">
function display_message()
{
alert("This is a message.");
};
</script>
<body>
<img src="image.jpg">
<form>
<input type="button" value="Click me!" onclick="display_message()" />
</form>
</body>
</html>
I know this is an old post, but this could be helpful...
Using jquery is great way to combine html elements with script
Note: This would be used in the body, if using it in the be sure to enclose it in
$(document).ready (function(){ YOUR CODE });
// Create an object:
var url = {
link: "https://stackoverflow.com/questions/2834929/how-can-i-use-html-tags-in-javascript"
};
// Display URL object:
$('#panel').html('<a href=' + url.link + '>' + url.link + '</a>');
//Note: the # denotes id, if you want to use a class it would be:
//$('.panel').html('<a href=' + url.link + '>' + url.link + '</a>');
//your html would be: <div id="panel"></div> or whatever you choose ie <p> and so //forth