Is there a way to use javascript to modify a script element?
Like for example:
HTML:
<script id="something" src="/js/file.js"></script>
Javascript:
var something = document.getElementById("something");
something.src = "/js/anotherfile.js"
Is it possible? Because I have a bit of code that works like that and it sort of doesn't work
To be specific, here's the code:
<!DOCTYPE html>
<html>
<head>
<title>MyohTheGod's Website</title>
<link rel="icon" type="image/x-icon" href="/supercorn.gif" defer>
</link>
<link id="css" href="/css/dark.css" rel="stylesheet" type="text/css">
</link>
<script src="/js/particles.js" defer></script>
<script src="/js/header.js"></script>
<script src="/js/theme.js"></script>
<script>window.alert("Welcome to the Home of MyohTheGod. You can play games, check out our web proxies, and more. Also, please do check out the About page. Press OK to continue...");</script>
</head>
<body>
-snip-
</body>
<script id="foot" src="/js/footer.js"></script>
</html>
<script>
-snip-
</script>
var css = document.getElementById("css");
var foot = document.getElementById("foot");
function toggleDLmode(m) {
-snip-
if (dlmodebool) {
css.href = "/css/dark.css"
foot.src="/js/dark-footer.js"
} else {
css.href = "/css/index.css"
foot.src="/js/footer.js"
}
}
-snip-
It is working, do you inspect it? It does changed, but maybe you're thinking, "hm why this /js/anotherfile.js is not downloaded?". Well because of the script tag is already rendered and already downloaded, so you can't do that. What you can do though add NEW script tag.
Maybe this will help How to dynamically change the script src?. This links would explain more why your code "does not work".
There certainly is. You can use document.scripts which returns an collection that you can iterate through like an array. You can change the code using the innerHTML property very much like a normal element. See here https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection
Edited to add: If you've got a html page with multiple script tags, the document.script collection has each script in the order they appear. The code below will log out the source (src tag) or the actual javascript for each script element.
You can also 'write' javascript by setting the innerHTML property.
IMHO it's a bit of a solution that's looking for a problem but at least it gives you access to the number of scripts you have.
[...document.scripts].forEach(script => {
if (script.src != '') {
console.log("Script source:" + script.src);
} else {
console.log(script.innerHTML);
}
});
Related
On my index page I have a number of includes.
<section><?php include('content/content1.php') ?></section>
<section><?php include('content/content2.php') ?></section>
<section><?php include('content/content3.php') ?></section>
In each of them I have a unique script (and some other things which is not shown here).
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Content1</title>
<link rel="stylesheet" href="content/sketch.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.10/p5.js"></script>
</head>
<body>
<div class="frame">
<canvas></canvas>
</div>
<script src="content/content1.js"></script>
</body>
The <canvas> tag is what the querySelector in the javascript calls to.
var canvas = document.querySelector('canvas');
This works, but only for the first content file. It seems the querySelector looks at the whole loaded page, instead of just inside the body of the document where the script is placed. Google console says: "Indentifier 'canvas' has already been declared".
I have tried setting an id on the canvas-element:
<canvas id="canvas1"></canvas>
var canvas = document.querySelector('#canvas1');
But it's not working. How do I get around this?
You can use document.currentScript to get the tag of the currently running script tag. From there, you can navigate to its containing section, and from there, get to the canvas descendant.
You should also put everything into an IIFE to avoid global variable collisions.
(() => {
const canvas = document.currentScript.closest('section').querySelector('canvas');
// ...
})();
Okay so, I once tried this a long time ago and it never happened before.
if I do
var blocks = 0;
document.getElementById('blocks').value = blocks;
Uncaught TypeError: Cannot set property 'value' of null
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<link rel="stylesheet" href="/css/Index.css">
<script src="/js/Index.js"></script>
</head>
<body>
<input type = "text" id="blocks"/>
</body>
</html>
Try moving your script to the bottom of the body. Element does not exist at the time of execution.
<head>
<title>Home</title>
<link rel="stylesheet" href="/css/Index.css">
</head>
<body>
<input type = "text" id="blocks"/>
<script src="/js/Index.js"></script><!-- here-->
</body>
If your script is saved in its own JS file (i.e. not as a <script> tag in the HTML), you cannot access DOM elements until the document is loaded. So, wrap your code in an onload event handler:
document.onload = function() {
var blocks = 0;
document.getElementById('blocks').value = blocks;
}
Try placing the <script> tag at the end of your <body> element to ensure that the element is accessible at the time the script is called:
<!DOCTYPE html>
<head>
<title>Home</title>
<link rel="stylesheet" href="/css/Index.css">
</head>
<body>
<input type = "text" id="blocks"/>
<script src="/js/Index.js"></script>
</body>
load your script in footer section or very end of the body instead of head. Your script is executing before DOM is loaded or call the specified statements under load event.
This is failing because your script is running before the DOM is finished rendering. You should always place your DOM-manipulating script inside document.onload function, which runs after the DOM has finished loading.
Also, you should always check for NPE (NullPointerException); it's a good habit to get into:
document.onload = () => {
const element = document.getElementById('blocks');
if (element) {
element.value = 0;
} else {
// consider publishing some warning
console.error("Could not find element #blocks");
}
}
As others have suggested, the common practice to ensure your script runs after elements have loaded is to move the script tag to the bottom of the body, after the elements themselves. However, a more modern approach is to use the defer attribute on your script tag: this ensures the script won't load until your DOM has loaded, but you don't need to worry about the tag's placement in the page relative to DOM elements you'll be manipulating. It's supported by all modern browsers, even IE10+.
So simply add defer onto your existing <script> tag and everything should work :)
I want to replace the current script tag with the HTML contents generated by the same script.
That is, my Page is
<html>
<body>
<div>
<script src="myfile1.js"></script>
</div>
<div>
<script src="myfile1.js"></script>
</div>
</body>
</html>
Inside each .js file corresponding html contents are generated. I want to put the contents as the innerHTML of the parent div. But can't set id for the parent div because the page is not static. So the current script tag must be replaced with the HTML content. How can I do this?
For each script tag src is the same. So can't identify with src. These scripts displays
some images with text randomly. Scripts are the same but displays different contents in divs on loading
Please help me
try inside of myfile1.js:
var scripts = document.getElementsByTagName( "script" );
for ( var i = 0; i < scripts.length; ++ i )
{
if ( scripts[i].src == "myfile1.js" )
{
scripts[i].parentNode.innerHTML = "new content";
}
}
This is a great question for those trying to implement a JSONP widget. The objective is to give the user the shortest possible amount of code.
The user prefers:
<script type="text/javscript" src="widget.js"></script>
Over:
<script type="text/javscript" src="widget.js"></script>
<div id="widget"></div>
Here's an example of how to achieve the first snippet:
TOP OF DOCUMENT<br />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
// inside of widget.js
document.write('<div id="widget"></div>');
$(document).ready(function() {
$.getJSON('http://test.com?remote_call=1', function(data) {
$('#widget').html(data);
});
});
<br />BOTTOM OF DOCUMENT
Have a look at: http://alexmarandon.com/articles/web_widget_jquery/ for the correct way to include a library inside of a script.
document.currentScript has been available since 2011 on Firefox and 2013 on Chrome.
document.currentScript documentation at MDN
<!DOCTYPE html>
<meta charset="UTF-8">
<title>currentScript test</title>
<h1>Test Begin</h1>
<script>
document.currentScript.outerHTML = "blah blah";
</script>
<h1>Test End</h1>
Unfortunately a running JavaScript file is not aware of where it is running. If you use document.write() in the script, the write function will take place wherever the script runs, which would be one way to accomplish what you want, but without replacing the contents or being able to perform any actions on the enclosing DIV.
I can't really envisage a situation where you'd have such stringent restrictions on building a page - surely if the page is dynamic you could generate identifiers for your DIV elements, or load content in a more traditional manner?
Why not use Smarty?
http://www.smarty.net/
You can use javascript in Smarty templates, or just use built-in functions.
Just take a look at http://www.smarty.net/crash_course
poof -- old answer gone.
Based on your last edit, here's what you want to do:
<html>
<head>
<!-- I recommend getting this from Google Ajax Libraries
You don't need this, but it makes my answer way shorter -->
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function getRandomContent(){
// I expect this is the contents of your current script file.
// just package it into a function.
var rnd = Math.random();
return "[SomeHtml]";
}
$('.random').each(idx, el){
$(this).html(getRandomHtmlContent());
});
});
</script>
</head>
<body>
<div class="random">
</div>
<div class="random">
</div>
</body>
</html>
If you don't mind the script tag remaining in place you can use something as simple as document.write().
myfile1.js:
document.write("<p>some html generated inline by script</p>");
It will do exactly what you need.
I'm writing text to a page using document.write for a Chrome extension, but the associated custom CSS isn't applied:
<!DOCTYPE html>
<html>
<head>
<title>TITLE GOES HERE</title>
<link rel="stylesheet" href="css/popup.css" type="text/css" />
</head>
<body>
<script type="text/javascript">
...
function showFolder(folder) {
console.debug('FOLDER: '+folder.title);
document.write('<p>'+folder.title+'<br></p>');
}
</script>
</body>
</html>
The CSS is simple, just for debugging:
p {
color: red;
}
I can get it to work if I put the stylesheet link inside the function showFolder, but that can't be the proper way to do it. I'm learning jscript/CSS on the fly, so the answer is probably something remedial. Is the problem in the jscript, the CSS or both?
Use innerHTML.
<div id="towrite"></div>
then you can write in it like this:
div=document.getElementById('towrite');
div.innerHTML = '<p>'+folder.title+'<br></p>';
If you run your document.write() before the page finishes loading (perhaps calling your showFolder call directly from a script on the page), then the text will be written into the document as you might expect.
However, if you call document.write after the page loads, as in an event handler, you will be writing an entirely new page. This is usually not what you want.
Instead, follow Zoltan's advice and set the innerHTML property of an empty div.
I'm not javascript expert... I mainly use jQuery.. but try this, kind of makes sense:
<!DOCTYPE html>
TITLE GOES HERE
<script type="text/javascript">
...
function showFolder(folder) {
console.debug('FOLDER: '+folder.title);
document.write('<p>'+folder.title+'<br></p>');
}
</script>
<link rel="stylesheet" href="css/popup.css" type="text/css" />
EDIT:
So the above didn't work, but I just thought about another solution. When are you actually calling the function? Try to put it in <body onLoad="functionnamehere()">
No idea if that works, but give it a try.
Really getting in to javascript and looking around at some patterns. One I have come accross is the module pattern. Its seems like a nice way to think of chucks of functionality so I went ahead and tried to implement it with jQuery. I ran in to a snag though. Consider the following code
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>index</title>
<script type="text/javascript" charset="utf-8" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
var TestClass2 = (function(){
var someDiv;
return {
thisTest: function ()
{
someDiv = document.createElement("div");
$(someDiv).append("#index");
$(someDiv).html("hello");
$(someDiv).addClass("test_class");
}
}
})();
TestClass2.thisTest();
});
</script>
</head>
<body id="index" onload="">
<div id="name">
this is content
</div>
</body>
</html>
The above code alerts the html content of the div and then adds a class. These both use jQuery methods. The problem is that the .html() method works fine however i can not add the class. No errors result and the class does not get added. What is happening here? Why is the class not getting added to the div?
Ah, now that you've updated your question I can better answer your question. You should change the append to appendTo considering you're wanting to move the newly created element inside of the already present #index.
$(document).ready(function() {
var TestClass2 = (function() {
var someDiv = $("#name");
return {
thisTest: function() {
someDiv = document.createElement("div");
$(someDiv)
.html("hello")
.addClass("test_class")
.appendTo("#index");
}
}
})();
TestClass2.thisTest();
});
Hope this helps!
I copied and pasted your code and it works for me.
Make sure you're not simply viewing source to see if the class is applied because doing so simply shows you the HTML that was sent from the server - any DOM updates that occur through JavaScript will not be reflected.
To view the live DOM, use a tool like Firebug or WebKit's Inspector (comes built-in to Safari and Chrome).
Your code works great!
http://jsfiddle.net/lmcculley/p3fDX/