So the question is, why doesn't this append the div's on load? I'm scratching my head on this one. No errors... Just not loading.
<head>
<script type="text/javascript">
function load() {
var divTag0 = document.createElement("div");
divTag0.className = "newsBlock";
divTag0.innerHTML = " Try this..";
document.getElementById("newsLeft").appendChild(divTag0);
var divTag1 = document.createElement("div");
divTag1.className = "newsBlock";
divTag1.innerHTML = " Blah..";
document.getElementById("newsRight").appendChild(divTag1);
var divTag2 = document.createElement("div");
divTag2.className = "newsBlock";
divTag2.innerHTML = " And this ..";
document.getElementById("newsLeft").appendChild(divTag2);
}
</script>
</head>
<body>
<p> Something filler </p>
<div id="newsLeft">
</div>
<div id="newsRight">
</div>
<script type="text/javascript">
window.onload="load()";
</script>
</body>
You are supposed to supply a string to getElementById ...
So that:
document.getElementById(newsLeft).appendChild(divTag0);
Should be:
document.getElementById("newsLeft").appendChild(divTag0);
But the main problem is:
window.onload="load()";
Which should be:
window.onload=load;
Thanks to jvillars for the fiddle, which helped me notice this.
If azhrei's answer doesn't work, the only thing I could think of would be that calling onload after it has loaded might not trigger, you can change this from your example by simply calling load();
I tested it here
Hope this helps
EDIT:
I believe azhrei has the right of it, it's not so much that the onload isn't triggering, it's that there's a syntax problem with your onload call.
But this code can also be improved in terms of better style (more readable/ easier to comprehend) by removing the second JS call.
In the header if you write:
window.onload = function() {
//everything inside your load() function goes here
}
It works just as well. It also removes a lot of the fluff that was just kind of there. I hope that helps.
Related
var Period =1;
if(Period==1){
document.getElementById("Main").style.backgroundImage = "url('Main_Background_Grass_1.png')";
}
For some reason this wont work. The image location is correct but im sure there is something wrong.
im pretty new to javascript
heres more code
<script type="text/javascript">
var Knowledge = 0;
var Period =1;
if(Period==1){
document.getElementById("Main").style.backgroundImage = "url('Main_Background_Grass_1.png')";
}
</script>
<div id="Main">
<div id="Toolbar">
Oh noes! Something Went Wrong
</div>
</div>
the image wont show up at all
The element isn't found at the time you call your function, place the javascript right before the closing body tag
<div id="Main">
<div id="Toolbar">
Oh noes! Something Went Wrong
</div>
</div>
<script type="text/javascript">
var Knowledge = 0;
var Period =1;
if(Period==1){
document.getElementById("Main").style.backgroundImage = "url('Main_Background_Grass_1.png')";
}
</script>
Uncaught TypeError: Cannot read property 'style' of null
That's because the element wasn't loaded yet. There are two ways to make sure a code runs only when a page is ready. One is to put the code at the bottom of the body, so the page has already been loaded. The other is to put it in an event listener for the window load event:
<script type="text/javascript">
window.addEventListener("load", function(e) {
// code goes here
});
</script>
Which one is the best practice? That's an eternal debate. I prefer the listener so that the code is all at the top, but many would disagree.
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/
In the following code I simply want the number of matched element by tag name, But it returns 0 and it alerts while page load (not on click as I want). Cannot find any mistake over an hour
<!DOCTYPE HTML>
<HTML>
<head>
<script language="javascript">
document.getElementById("all").onclick = alert( document.getElementsByTagName("a").length);
</script>
</head>
<body>
<div id="all" class="a">Click</div>
<div class="a"></div>
<div class="a"></div>
</body>
</HTML>
I'm a total newbie in JavaScript
A couple of problems. The first one is pointed by #Ian in his comment on your question and the second one is you are calling getElementsByTagName("a") when in your code you do not have any <a> tags. You need to call getElementsByClassName("a") instead.
document.getElementById("all").onclick = function() {
alert( document.getElementsByClassName("a").length);
}
Update:
After Ian's comment, double checked jsfiddle and found that it had onLoad selected. So here is the corrected code with window.onload and updated jsfiddle:
window.onload = function() {
document.getElementById("all").onclick = function() {
alert( document.getElementsByClassName("a").length);
};
};
Here is the jsfiddle of this.
You are running the JS before even DOM is loaded. That means element all does not exist in the DOM when JS is running. Write like below, and that is the way to do.
var attachEve = function(){
document.getElementById("all").onclick = function() {
alert( document.getElementsByClassName("a").length);
}
}
window.onload = attachEve;
It should work!. Without window.onload works in jsfiddle because jsfiddle runs the JS in window.onload context.
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.
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.