This question already has answers here:
Can scripts be inserted with innerHTML?
(26 answers)
Closed 9 years ago.
i dont know a lot of javascript but one thing ive realized is doing this
function example()
{
document.getElementById("example").innerHTML="<script>document.write(example)</script>"
}
doesnt work! i understand this but is there another way of doing this same thing that does work?
This approach worked for me:
<body>
<div id="main">
</div>
<script>
// create a script element
var script = document.createElement('script');
// fill its inner html with js code
script.innerHTML = 'alert("Javascript");'
// add it inside your target div and then profit!
document.getElementById('main').appendChild(script);
</script>
</body>
Edit:
I've found more info about your problem here, I suggest you read the question, it has plenty of helpful answers and it also explains why your first approach did not work: Can scripts be inserted with innerHTML?
A simple vanilla approach of using this code to write data inside a div after the page has loaded could be done like this:
<html>
<head>
<script>
window.onload = function () {
var script = document.createElement('script');
script.innerHTML = 'alert("Javascript");'
document.getElementById('main').appendChild(script);
}
</script>
</head>
<body>
<div id="main">
</div>
</body>
</html>
There is two error on your script. This is doesn't work, because variable name and function name equal to div id and this wrong method for javascript. You write a code to your div, but you don't run it. You can try that;
<div id="mydiv"></div>
<script>
function example()
{
document.getElementById("mydiv").innerHTML = eval("document.write('lololo')");
}
example();
</script>
Related
This question already has answers here:
How to make the HTML renders before the alert is triggered?
(4 answers)
placing <script> tags right before </body> doesn't work as expected
(3 answers)
Closed 1 year ago.
My javascript is running before my HTML loads, even if I put it right before the like this:
<body>
<h1>Title</h1>
<script>
alert("yo");
</script>
</body>
Any ideas why that may be happening?
Any ideas why that may be happening?
alert is blocking, script evaluation comes before DomContentLoaded (DCL) and subsequent first content paint (FCP) which is why it doesn't show Title before alert starts blocking the dom.
You could run it this way:
<body onload="alert('yo')">
<h1>Title</h1>
</body>
Or this way:
<body onload="my_function()">
<h1>Title</h1>
<script>
function my_function() {
alert('yo');
}
</script>
</body>
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 3 years ago.
I'm trying to use function closure in my javascript as follows:
In my html file:
<head>
<script src="myscript.js"></script>
</head>
<body>
<section id="mysectionId"></section>
</body>
In myscript.js:
(function() {
var id = document.getElementById('mysectionId');
console.log(id);
}());
However, id seems to equal null. I'm not sure what I've done wrong - does function closure scope exclude globals like 'document'? If so, how come I can still use 'console.log()' inside the function closure?
You're javascript is running before your html loads. Put your script tag after your html content at the very bottom of the body
<head>
// put css here
</head>
<body>
<section id="mysection"></section>
<script src="myscript.js"></script>
</body>
This question already has answers here:
when and where to put javascript in html
(7 answers)
Closed 9 years ago.
the thing is i'm unable to figure out where to embed javascript in html page whether in head section or body section.
example 1:
<html>
<head>
<title>events</title>
<script>
document.getElementById("b").onclick=function(){displayDate()};
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>
</head>
<body>
<p id="demo"></p>
<button id="b">new</button>
</body>
</html>
in the above example I placed script tags in head section but it is not working.
example: 2
<html>
<head>
<title>events</title>
<script>
function upper()
{
var x=document.getElementById("t");
x.value=x.value.toUpperCase();
}
</script>
</head>
<body >
enter some text:<input type="text" id="t" onChange="upper()"/>
</body>
</html>
in the second example I placed the javascript in head section it is working properly.first example demonstrates that on clicking a button date will be displayed in the second example in a text box when data is entered and if we come out of the box the letters in the box will we converted to uppercase.
To have it more readable I prefer to always place JavaScript in the head section. If you need to access elements from there, use the window.onload event:
<head>
<title>events</title>
<script type="text/javascript">
window.onload = function() {
document.getElementById("b").onclick = function() {
displayDate();
};
};
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>
</head>
This would work just fine.
Your second example worked because you just defined a function, you didn't try to access any element.
You can put it in the head. The problem is that your examples are not the same. The first one doesn't work because the current date is retrieved by calling Date(), when it should be new Data().getDate(). The second example works because the code is valid.
The problem you're running into is that you're trying to reference an element before it is loaded into the DOM.
When you're putting the script in the HEAD tag, the dom hasn't been loaded yet and the document.getElementById won't find what you're looking for.
You have a few different options to deal with this. You can put the script at the end of the page, which will work for your small example here.
Probably a better option is to take a look at learning/using jquery or another js utility. Jquery makes it easy to solve this issue by giving you a "ready" event. This ready event will be triggered when the DOM is fully loaded. So:
$(document).ready(
function()
{
$("#demo").html((new Date()).toString());
});
Is all you really need. With this approach, it doesn't matter where the script it on the page.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is It Possible to Sandbox JavaScript Running In the Browser?
I would like to give the user the ability to input JavaScript in a textarea like this:
<!DOCTYPE html>
<html>
<head>
<script>
function lapzwans()
{
var d = document.getElementById("area").value;
document.getElementById("blahblah").innerHTML = d;
}
</script>
</head>
<body>
<h1>Javascript in Javascript</h1>
<p>This experiment attempts to launch a script from another script.</p>
<p>Enter your script in the text area</p>
<textarea type="text" id="area"></textarea>
<button onclick="lapzwans()">Click here</button>
<p id="blahblah"></p>
<p id="deegroller">Make this text green</p>
</body>
</html>
I have tried this, but I get no result.
Is it impossible to do this, or am I doing things wrong?
Thanks in advance.
One possible answer:
eval(/* some JS here */);
Note though that what you are trying to do can be dangerous (in some cases) as you are allowing user-written arbitrary JS to be executed.
Related reading:
How evil is eval?
When is JavaScript's eval() not evil?
the eval method takes whatever string is passed to it and tries to run it.
eval("alert('foo')");
will alert "foo";
You don't need to use the evil eval to do this.
function lapzwans()
{
var d=document.getElementById("area").value;
document.getElementById("blahblah").innerHTML=d;
var userScript = new Function(d);
userScript();
}
<body>
<div id="outer">
<script>var e = document.createElement("div");
e.id = "inner1";
document.body.appendChild(e);</script>
<script>document.write("<div id='inner2'></div>");</script>
The structure I want would be:
html>body>div#outer>div#inner1+div#inner2
the structure I get is:
html>body>(div#outer>div#inner2)+div#inner1
This is terrible beyond my ability to describe, but appears to work for your given situation (I can't tell if you want inner1 and inner2 as children or siblings of outer. this arranges them as siblings).
<body>
<div id="outer">
<script>
var e = document.createElement("div");
e.id = "inner1";
document.body.appendChild(e);
</script>
<script>
var scr = '<script>';
scr += "document.write(\"</div><div id='inner2'>\"); ";
scr += '<' + '/script>';
document.write(scr);
</script>
the closing </script> string is divided to keep the parser from imploding.
how about this?
<script>
// document.write("<div id='inner2'></div>");
var inner2 = document.createElement('div');
inner2.id = 'inner2';
//document.getElementById('outer').appendChild(inner2); //as a child of outer
document.body.appendChild(inner2); // as a sibling of outer
</script>
Look into the jquery documentation. Jquery is a javascript library that you include in your page header. It provides a ton of useful methods for working with the DOM. jQuery is my first choice for writing javascript these days. Straight up js just feels old school to me now. Knowing how to use jQuery effectively (or at least some js library) is a skill every web developer should have. jQuery provides methods like $('css-selector-here').append('what you want to insert'), .prepend(), .insertBefore(), insertAfter(), and .html(), among many others, one of which would probably suit your needs.
Here is a list of all the DOM manipulatuion methods:
http://api.jquery.com/category/manipulation/
Can I clarify your question?
You are getting the following:
<html>
<body>
<div id='outer'>
<div id='inner2'></div>
</div>
<div id='inner1'></div>
</body>
</html>
But what you want is:
<html>
<body>
<div id='outer'>
<div id='inner2'></div>
<div id='inner1'></div>
</div>
</body>
</html>
As long as your div#outer is already defined, you can do the following using jQuery. Quick and easy copy & paste. Please give it a shot!
//If you don't already have jQuery, load it from CDN
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { //Executes after DOM is ready
$("#outer")
.append("<div id='inner1'>INNER DIV 1</div>")
.append("<div id='inner2'>INNER DIV 2</div>");
});
</script>