I have a project that uses jQuery. And I am trying to convert this script to Javascript. I had the following line on that script.
var a = $("#myImage");
I changed it to
var a = document.getElementById("myImage");
but script is not working because my page hasn't loaded yet when this happens. I have no idea how to fix this. Any help would be greatly appreciated. Thank you.
<body onload="var a = document.getElementById("myImage");">
</body>
onload="var a = document.getElementById("myImage");" runs when the content is fully loaded. When the body is completely loaded then var a = document.getElementById("myImage"); will run.
You need to execute the script once the page loads.
window.addEventListener("load", function(){
// .... Add your script here
});
You can include a listener on the document object to wait for the DOM to be loaded.
document.addEventListener('DOMContentLoaded', function(event) {
var a = document.getElementById("myImage");
})
Try using.
window.addEventListener('DOMContentLoaded', function(){
var a = document.getElementById("myImage");
//Rest code here
});
You could, for instance:
Place corresponding <script> tag before closing </body> tag.
Start doing things when document is loaded using a callback.
Personally, I prefer the 1st option much more since it works more stably according to my experience.
Related
Help me please! Why this code not work? It does not show alert.
var jqueryScript = document.createElement('script');
jqueryScript.src =
'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js';
jqueryScript.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(jqueryScript);
$(function() {
$("#main").click(function() {
alert("asdasd");
});
});
Thank you in advance!
Probably because jQuery lib is not loaded as it loads asynchronously made that way, and no one can guarantee you when it will load on time, which is not that way if you load it by <script> tag, so $(function() { ... }); won't work as $ which represents $.jQuery( is not initialized yet. If you execute the script second time without reloading the page, it will work, as jQuery will be loaded from the first execution, even its made in wrong time.
So I'm not that great with Javascript so I'll put that forward right away. That being said, I've looked up as much as I could on this particular problem before asking, but the suggestions haven't solved my issues. I'm ultimately trying to pull all of the links from an iframe window on the same domain as the main page. Then I want to basically search that link array to match it with the current page to trigger a CSS modification to the html code (this part is not coded yet, FYI). So here is the part I have so far: Side note: The confirms are in there to debug the code and try to tell me where it's failing and what my queries are returning, they won't stay obviously when this is finished. I appreciate any advice that may help me fix this!
<script type="text/javascript">
// main is the iframe that I'm trying to search for a tags
document.getElementById("main").onload = function() {
confirm("test");
var main = document.getElementById("main");
var anchors = main.contentWindow.document.getElementsByTagName('a');
confirm(anchors[1]);
for (var i in anchors) {
confirm(anchors[i].getAttribute("href"));
}
};
</script>
I have created a plunker for you its working. I think its the placement of code in your file is causing the problem.
<iframe id="main" src="content_if.html"></iframe>
<script>
// main is the iframe that I'm trying to search for a tags
document.getElementById("main").onload = function() {
confirm("test");
var main = document.getElementById("main");
var anchors = main.contentWindow.document.getElementsByTagName('a');
confirm(anchors[1]);
for (var i in anchors) {
confirm(anchors[i].getAttribute("href"));
}
};
</script>
You should use jQuery to do this in a cross browser way. Include jQuery in page
<script src="https://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
and follow this post
There is a similar post about doing this and I agree with Mohamed-Yousef. If you can use jquery then you should do so!
$("#main").contents().find("a").each(function(element) {
// "each" will iterate through every a tag and inject them as the "element" argument
// visible in the scope of this anonymous function
});
EDIT:
You must include
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
above your code that references the $ variable. There are other ways to use jQuery but this is probably the easiest.
Instead of copy/pasting the code below from browser update on every page, I'd like to include it in a scripts.js file.
My question is: do I need to wrap the code into something, for instance $(function() { since I will remove the <script> tags?
Thanks
<script type="text/javascript">
var $buoop = {};
$buoop.ol = window.onload;
window.onload=function(){
try {if ($buoop.ol) $buoop.ol();}catch (e) {}
var e = document.createElement("script");
e.setAttribute("type", "text/javascript");
e.setAttribute("src", "//browser-update.org/update.js");
document.body.appendChild(e);
}
</script>
That code is horrible :-/ It simply dynamically loads the http://browser-update.org/update.js script in a window.onload handler.
If you want to load it as an external script, you can just directly load it:
<script type="text/javascript" src="//browser-update.org/update.js" async></script>
Do I need to wrap the code into something, for instance $(function() {, since I will remove the <script> tags?
No, you don't. However, if you have jQuery available, then you might simply use
$(function() {
$.getScript("//browser-update.org/update.js");
});
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();
});
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.