I have the follwing JavaScript.
<html>
<head>
<script language="JavaScript">
function fdivisible()
{
document.write("<h1> Just a javascript demo</h1>");
var x=document.forms["aaa"]["txt1"].value;
alert(x);
}
</script>
</head>
<body>
<form action="#" name="aaa">
Enter a no. : <input type="text" name="txt1" id="txt1" />
<input type="button" value="Click" onclick="fdivisible();">
</form>
</body>
</html>
The problem is, the first line of the JS function is executing and the rest are ignored. If I comment out the first line the rest of the code is executed. Can anybody explain to me why it is so?
Because calling document.write implicity calls document.open, which clears the document on which it has been called:
If a document exists in the target, this method clears it
After the call to document.write, the element you're trying to get a reference to no longer exists in the DOM, and an error is thrown. If you look in the error console it should be something along the lines of the following:
TypeError: Cannot read property 'txt1' of undefined
document.write can only be used during the initial loading of the document.
If you want to insert your H1 when the function is called, you may replace
document.write("<h1> Just a javascript demo</h1>");
with
var h1 = document.createElement('h1');
h1.innerHTML = " Just a javascript demo";
document.body.appendChild(h1);
document.write(content) writes content on the document stream.
You have to close the stream after writing on the document in order to continue the page loading
document.write("hello");
document.close();
https://developer.mozilla.org/en-US/docs/DOM/document.write
https://developer.mozilla.org/en-US/docs/DOM/document.close
https://developer.mozilla.org/en-US/docs/DOM/document.open
With addition to dystroy answer, you could replace document.write with:
document.body.innerHTML += '<h1>Javascript demo</h1>
You're destroying the DOM with your document.write call. In some browsers, this also destroys global variables.
Instead use:
var element = document.createElement('h1');
element.appendChild(document.createTextNode('text'));
document.body.appendChild(element);
use document.write() at the end of all JS statements. The script element is never executed after it.
Try this:
var x=document.getElementById(txt1).value;
alert(x);
You can write to the document with
document.write("<h1> Just a javascript demo</h1>");
only once and it applies to the whole document. If you want to put you will have to add a class/id to it and then put text in that class/id.
Related
I'm trying to get the entire HTML of a page, but it seems that the text stops after </head>. The following code is essentially how I tested this. What am I doing incorrectly here?
<html>
<head>
<script>
document.onload = showHTML();
function showHTML() {
html = document.documentElement.innerHTML;
alert(html);
}
</script>
</head>
<body>
<p> This is absolutely useless text. </p>
</body>
</html>
Okay here is a complete working answer... after checking already posted answer I realized it didn't work for multiple reasons..
First you need to put a function in the onload event. The onload event is written without uppercases.
Also! you need to put the event on the window object as such:
window.onload = showHTML;
Here is a fiddle. Notice on the left that it isn't wrapped inside onload. It's unwrapped in head like your code should be.
http://jsfiddle.net/4zsGH/2/
You should have something like this:
<html>
<head>
<script>
window.onload = showHTML;
function showHTML() {
var html = document.documentElement.outerHTML;
alert(html);
}
</script>
</head>
<body>
<p> This is absolutely useless text. </p>
</body>
</html>
Take off the parenthesis from document.onLoad = showHTML();
What's happening is showHTML() is being called right away, before the rest of the document is being loaded. Taking off the parenthesis means the function is being set to the onLoad callback.
Try:
<html>
<head>
<script>
document.onload = showHTML;
function showHTML() {
var html = document.documentElement.outerHTML;
alert(html);
}
</script>
</head>
<body>
<p> This is absolutely useless text. </p>
</body>
</html>
When you wrote document.onLoad = showHTML(); you didn't assign the reference to showHTML function to document.onLoad but you assigned the value returned by that function i.e. undefined (because you called it). I also changed innerHTML to outerHTML.
Also document.onload shouldn't be written in camel case.
Writing var html = … isn't essential but it wouldn't run in strict mode. Without it you create a html property on global object window implicitly.
I think this is what you are looking for:
document.onLoad = showHTML();
function showHTML() {
var html = document.documentElement.innerHTML;
alert(html);
}
http://jsfiddle.net/skhan/4zsGH/
I have this function which is trying to change the src property of an img. Here's the Javascript:
function transition(){
document.getElementById("firstfirst").src = marray[currArrayValue];
currArrayValue++;
if(currArrayValue == array.length-1){
currArrayValue = 0;
}
setTimeout(transition(), 1000);
}
My google chrome console is saying document.getElementById("firstfirst") doesn't exist, but it definitely does. Here's the HTML:
<div id="banners-container">
<div id="banners">
<img src="images/banners/top-banner-one.png" id="firstfirst" alt="Subscribe now to get access to thousands of vintage movies!" border="0">
</div>
</div>
What gives?
Javascript is executed as soon as it has been parsed.
If your JS is included in the <head> of your webpage, it will be executed before the document body has been parsed and the DOM has been built.
As such, you need to engineer your code so that it is not executed until the DOM has been loaded. You might want to look at the MDN docs on the DomContentLoaded event. Alternatively, you can use one of the many JavaScript libraries out there which wrap this up for you.
if chrome says the element is null it is null. Perhaps you are calling function before the element loaded in DOM. like calling the function in head tag prior the element tag.
so try something like this.
<html>
<head>
<script>
function F () { /*reach element*/ }
</script>
</head>
<body>
//The element
</body>
<script>
F ();
</script>
</html>
I have tried, as many have suggested, saving a variable as the .value or .innerHTML of an ID, found by using document.getElementById. Here is all of my HTML:
<html>
<head>
<title>write</title>
<script type="text/javascript" src="g.js"></script>
<link rel="stylesheet" type="text/css" href="g.css" />
</head>
<body>
<div id="box">
<textarea id="txt" placeholder="placeholder. type here.">text text</textarea>
</div>
</body>
</html>
and here is my javascript, currently meant to fire an alert that contains the text in the text area – right now that would be, text text:
function run(){
var txt = document.getElementById('txt');
alert(txt);}
run()
Right now, loading the page fires an alert with the text Null and adding .value after getElementById('txt') results in no alert. Many thanks in advance.
The problem is that your javascript is executing before the DOM is constructed. When you load the JavaScript file in the <head> of the document, it is executed immediately, before the <textarea> tag has been created.
Try moving your script block below the textarea, just before the </body> tag.
Here's an example: fiddle
After the DOM is constructed you can use getElementById just as have and can access the contents of the textarea with the value attribute. All of this is in the fiddle above.
Alternatively, you can wrap your run() method call with a library that provides an event when the DOM becomes ready. jQuery's example would be:
$(function () {
// code you want to execute when the DOM is ready.
run();
});
function run() {
var txt = document.getElementById("txt").value;
alert(txt);
}
$(document).ready(function(){
run();
});
check this jsfiddle link
You are not getting textarea value because your javscript function is getting executed before there's value in DOM
or using javascript
function run(){
var txt = document.getElementById("txt").value;
alert(txt);
}
window.onload = run();
More about window.onload
The javascript below works in firefox. In fact, if you click the answer button for this question, you can try it out in firebug on this very page...
var textArea = document.getElementById("wmd-input"); // #wmd-input is the text input where your answer goes...
alert( textArea.value );
Make sure you enter some text first, of course.
While you're at it, you should give jQuery a try:
alert( $("#wmd-input").val() );
Or better yet,
console.log($("#wmd-input").val());
Hope that helps.
The code for a counter gives an error
Whereas a similar snippet does not
I can't figure out any valid reason...
The line under consideration is:
<input type=button name="but2" value="stop" onClick="window.clearTimeout(ID);">
The complete code is:
<html>
<head>
<script language="JavaScript">
var counter=0;
ID=window.setTimeout("start();",2000);
function start()
{
counter++;
document.forms[0].elements[0].value=counter;
ID=window.setTimeout("start();",2000);
}
</script>
</head>
<body>
<form name="frm1">
<input type="text" name="timer1">
<input type="button" name="but1" value="start" onClick="counter=0; start();">
<input type=button name="but2" value="stop" onClick="window.clearTimeout(ID);">
</form>
</body>
</html>
Use window.start instead of start for the onClick event. It may be that IE doesn't create a window context when you use code instead of a function for the handler.
Everything about that code there is wrong. Please try to avoid that source of tutorials in the future.
Here is a working script: http://jsfiddle.net/teresko/qTJPx/
List of problem with your script:
missing doctype
language="JavaScript" is deprecated
variables ID and counter ended up in global scope
using html to attach events
incorrect use of setTimeout
<script> tag used in <head> when DOM is not ready yet
.. and i don't even want to go over that "similar snippet", it looks like something that by all rights should be dead an buried.
When you add your JavaScript code, it should be right before the closing </body> tag, because at that stage the DOM is already ready, but page has not begun to render yet.
I would strongly suggest for you to get some newer materials for learning JavaScript.
Hi I think in this line your getting the error
ID=window.setTimeout("start();",2000);
Right ?
Put this code
var ID=window.setTimeout("start();",2000);
you'll not get this JavaScript: Error Object doesn't support this action error.
I'm trying to write a javascript function that adds some DOM nodes to the document in the place it was called, like this:
...
<div>
<script type="text/javascript">
pushStuffToDOMHere(args);
</script>
</div>
...
i try to do it 'cleanly', without using node id property of the div, or innerHTML string manipulation. for that I need to know where in the document the script tag is located.
is there a way to do it?
Talking about cleanly, I don't think your approach is particularly clean. It is a much better idea to give the div a unique id and execute your javascript when the DocumentReady-event fires.
Do you have an overriding reason for doing it this way? If not the suggestion to use a unique id makes the most sense. And you can always use a library like jQuery to make this even easier for yourself.
However, the following quick test shows that if you use document.write() in the function then it writes the value into the place where the function was called from.
<html>
<head>
<script type="text/javascript">
function dosomething(arg){
document.write(arg);
}
</script>
</head>
<body>
<div>The first Div</div>
<div>The
<script type="text/javascript">
dosomething("Second");
</script>
Div
</div>
<div>The
<script type="text/javascript">
dosomething("Third");
</script>
Div
</div>
</body>
</html>
But, again the question, are you sure this is what you want to do?
Although I agree with n3rd and voted him up, I understand what you are saying that you have a specific challenge where you cannot add an id to the html divisions, unless by script.
So this would be my suggestion for inlining a script aware of its place in the DOM hierarchy, in that case:
Add an id to your script tag. (Yes, script tags can have ids, too.)
ex. <script id="specialagent" type="text/javascript">
Add one line to your inline script function that gets the script element by id.
ex. this.script = document.getElementById('specialagent');
...And another that gets the script element's parentNode.
ex. var targetEl = this.script.parentNode;
Consider restructuring your function to a self-executioning function, if you can.
Ideally it executes immediately, without the necessity for an 'onload' call.
see summary example, next.
SUMMARY EXAMPLE:
<script id="specialagent" type="text/javascript">
var callMe = function(arg1,arg2,arg3) {
this.script = document.getElementById('specialagent');
var targetEl = this.script.parentNode.nodeName=="DIV" && this.script.parentNode;
//...your node manipulation here...
}('arg1','arg2','arg3');
</script>
The following TEST code, when run, proves that the function has identified its place in the DOM, and, importantly, its parentNode. The test has division nodes with an id, only for the purpose of the test. They are not necessary for the function to identify them, other than for testing.
TEST CODE:
<html>
<head>
<title>Test In place node creation with JS</title>
</head>
<body>
<div id="one">
<h2>Child of one</h2>
<div id="two">
<h2>Child of two</h2>
<script id="specialagent" type="text/javascript">
var callMe = function(arg1,arg2,arg3) {
this.script = document.getElementById('specialagent');
var targetEl = this.script.parentNode;
/*BEGIN TEST*/
alert('this.script.id: ' + this.script.id);
alert('targetEl.nodeName: ' + targetEl.nodeName + '\ntargetEl.id: '+targetEl.id);
alert('targetEl.childNodes.length: ' + targetEl.childNodes.length);
var i = 0;
while (i < targetEl.childNodes.length) {
alert('targetEl.childNodes.'+i+'.nodeName = ' + targetEl.childNodes[i].nodeName);
++i;
}
/*END TEST - delete when done*/
//...rest of your code here...to manipulate nodes
}('arg1','arg2','etc');
</script>
</div>
</div>
</body>
</html>
Not really sure what your trying to achieve but this would pass the dom element to the function when clicked. You could then use jquery in the function to do what you wanted like so
...
<script type="text/javascript">
function pushStuffToDOMHere(element)
{
$(element).append("<p>Hello</p>"); // or whatever
}
</script>
<div onclick="pushStuffToDOMHere(this);">
</div>
...
my solution is a compbination of the (good) answers posted here:
as the function is called, it will document.write a div with a unique id.
then on document.onload that div's parent node can be easily located and appended new children.
I chose this approach because some unique restrictions: I'm not allowed to touch the HTML code other than adding script elements. really, ask my boss...
another approach that later came to mind:
function whereMI(node){
return (node.nodeName=='SCRIPT')? node : whereMI(node.lastChild);
}
var scriptNode = whereMI(document);
although, this should fail when things like fireBug append themselves as the last element in the HTML node before document is done loading.