Javascript giving error only on load - javascript

The following is the javascript I wrote in my js file:
var ele = document.getElementsByTagName('body');
var p = document.getElementById('hello');
ele[0].innerHTML= p.innerHTML;
But it gives error that p is null.
But when I run the same commands in console, they work perfectly.
Can someone please help me figure this out.

As users suggested, it's about if the DOM is rendered or not when you run JS. You have 2 options.
When you link the script in the <head>, make sure to wrap it in onload, see example below
When you link the script in the <body>, you don't need to wrap it in onload
// example
window.onload = function(){ // or better use window.addEventListener
// do some stuff or paste your code here
}

Related

Remove Script Tag

I hope you have well with nice pleasure.
I am trying to remove Script tag by ID. For this purpose, I am apply code
var elem = document.getElementById("sns_scripts");
elem.remove();
But, this is give me error on my console windows is :
Uncaught TypeError: Cannot read property 'remove' of null
I am trying another method is :
$("#sns_scripts").remove();
It is also not working. See Picture
Picture is mention , sns_scripts script still avaialbe, and above this script my custom code, but it is not working.
Please help me, I am really want to remove sns_scripts script from my webpage.
Wrap your code within DOMContentLoaded event:
document.addEventListener('DOMContentLoaded', function(){
var elem = document.getElementById("sns_scripts");
elem.remove();
});
Because you are trying to get an element at that point where is wasn't available in the DOM. So, it was null.
do not use elem.remove(), but use
$(elem).remove();
NOTE: Re-order following lines in your code. Because you are running remove() function before writing script with id(sns_script):
<script type="text/javascript" id="sns_scripts">var video=document.getElementById('bgvid');</script>
<script>
$('#sns_scripts').remove();
</script>

JSFiddle doesn't work even if I copy code from another working fiddle

I visited this link to get some help in learning how to play around with Javascript: http://jsfiddle.net/8ZtqL/1/
I attempted it on my project. Didn't work. Hmm.
So I made a new JS Fiddle and copied to code over. Still didn't work.. Why?
Here's my fiddle which doesn't work: https://jsfiddle.net/mt6bwry9/
The code is an exact copy.
Here's the code used:
var text="This text will be written one by one.";
var delay=200;
var elem = $("#myText");
//text- string
//elem - jQuery element where text is to be attached
//delay - the delay in each text
var addTextByDelay = function(text,elem,delay){
if(!elem){
elem = $("body");
}
if(!delay){
delay = 300;
}
if(text.length >0){
//append first character
elem.append(text[0]);
setTimeout(
function(){
//Slice text by 1 character and call function again
addTextByDelay(text.slice(1),elem,delay);
},delay
);
}
}
addTextByDelay(text,elem,delay);
<body>
<div id="myText"></div>
</body>
Since you said you're new to JavaScript, here is a little more detailed answer.
If your JavaScript isn't behaving the way you expect it to, definitely check your browser console. You can do that in Chrome by going to View>>Developer>>JavaScript Console or simply pressing Command+Alt+J. In other browsers you will find similar developer tools.
In the case of your JS Fiddle, when you open the console you see an error that says $ is not defined. $ is shorthand for jQuery. The JavaScript code that you've copied from the other Fiddle uses jQuery to do DOM Manipulation and your Fiddle hasn't loaded jQuery. So click on the gear icon in your JS section and under Frameworks select jQuery (I recommend 2.2.1) and try running your code again.

JavaScript code is not executed during the runtime of the code, but when I debug it and execute in console, it works

I have a following code:
var e = document.getElementById("overlay");
e.parentNode.removeChild(e);
This code is supposed to remove the DOM element, but it doesn't. So I removed the code and added a breakpoint in its stead and input the code in the console during the pause manually, and it worked (i.e. the element was successfully removed).
This behavior seems rather strange for me, so I wanted to ask, why does it happen and what can I do to inspect this peculiar issue?
Thanks in advance.
EDIT: Thanks for quick replies. Nonetheless, I want to make it perfectly clear that the element #overlay does exist at the time of the execution of the code. Moreover, when I put a debugging breakpoint at that place in the code and execute these two lines of code, it does have an effect on this particular existent element (which it doesn't without debugging).
EDIT 2: I was asked to clarify the code. I execute the following code before the body (part of the queryloader2 plugin, which ensures image preloading):
window.addEventListener('DOMContentLoaded', function() {
new QueryLoader2(document.querySelector("body"), {});
});
No errors present (except for a 404 error because of missing image, which has no impact on Javascript).
As Teemu mentioned #overlay more than likely doesn't exist when the code is run.
For a test.. Try wrapping your code in either of these...
Javscript
window.onload = function () { /*your code*/ };
Jquery (if included)
$(document).ready(function () { /* your code*/ });
You should execute your code after the DOM tree has finished loading. One option is to wrap your code in a function that executes after the DOMContentLoaded event has been fired.
document.addEventListener("DOMContentLoaded", function(event) {
// your code
});
Look at this answer for more information: $(document).ready equivalent without jQuery

Can someone explain to me how this is possible? (Picture in comments)

So I'm trying to link up my html and javascript files in notepad++, but it isn't working properly.
I wanted to know how it is possible that it writes test, but doesn't remove the div. Can anyone explain this? Thanks in advance!
1, jQuery isn't linked. Meaning, you don't have <script type='text/javascript' src='myjQueryfile.js'></script> in your HTML, you'll want to put it before your script.
2:
Because the element with the ID of blue, doesn't exist yet. The DOM - basically the object of your HTML - has yet to be constructed when your script is run, which in this case is the top of the page, before blue comes into existence. You'll want to use an event to fix this, typically $(function(){ ... }); which will execute your code when the DOM is ready.
Also, document.write just writes code then and there, meaning exactly where the document.write calls is made, the HTML will be outputted.
You should have linked jquery. You're trying to use it without having it linked.
The script is loaded in the head. At the time the script executes the body of the document is not built, so nothing is removed. If you were to use the document.ready callback (and had properly included jQuery) it would work
$(function(){ $("#blue").remove(); });
A plain js version of this is
window.onload = function(){
var b = document.getElementById("blue");
b.parentNode.remove(b);
};
At the time the script runs, only the portion of the document up to the <script> tag has been loaded. You need to delay until the DOM has fully loaded before the script can target the DOM:
document.addEventListener("DOMContentLoaded", function(event) {
$("#blue").remove();
});

document.write become invalid within Javascript file which is added by appendChild

when I add the script tag in body tag of my index.html directly, like below:
<script type="text/javascript" src='**doc_write_in_it.js**'></script>
It works well, the "test doc write" is output there.
But if I write in another way, like below:
<script type="text/javascript">
var model = document.createElement('script');
model.setAttribute('type','text/javascript');
model.setAttribute('src','doc_write_in_it.js');
var bd = document.getElementsByTagName('body')[0];
bd.appendChild(model);
</script>
document.write become invalid within Javascript file which is added by appendChild.
The alert in doc_write_in_it.js will show, but the text in document.write doesn't.
doc_write_in_it.js file is like this:
alert('activited');
document.write('test doc write");
Hope someone can help...
Thanks a lot...
as mentioned above, document.write does not work when the page has already been loaded.
I suggest use innerHTML property whenever you can.
example:
var bd = document.getElementsByTagName('body')[0];
bd.innerHTML = "some text";
document.write will overwrite anything else before it. So, if you are absolutely sure that it is what you want to be doing. Then you should probably wait for the page to load, and then fire the document.write. Something on the lines of the below..
<script>
function my_onload_fn() {
document.write("test document write");
}
</script>
<body onload="my_onload_fn();">
Actually, document.write can't affects when page is loaded, but you can invoke document.open() to make it posible.
Putting script code in script tag is synchronous, while loading script file via DOM manipulation is asynchronous, so,if the page is simple, page may have been loaded when document.write(..) runs and make document.write(...) do nothing if document.open() is not invoked.
alert('activited');
document.open();
document.write('test doc write');
document.close();
This will work.
And check this link to learn more.

Categories