Remove JavaScript code from page with JavaScript - javascript

I have a chunk of JavaScript code:
<script src='blah.js' type='text/javascript'></script>
How can this be removed or disabled with JavaScript?

If the script tag is received in a string via AJAX:
str = str.replace("<script src='blah.js' type='text/javascript'></script>", "");
However, if the script tag is in the current document, there is no way to disable it, because:
If it is in the part of the document which has already been parsed (i.e. above the current script), it has already been executed. While you can remove the script element, just like any element, there is no way to rewind time and automatically undo the effects the script has.
If it is in the part of the document which has not yet been parsed (i.e. below the current script), you cannot affect it, as it does not exist yet.

You can grab the script like any other element, you can do this:
document.querySelector("script").remove();
If you have a lot of script tags you can just grab the one you want like accessing a array element like so:
document.querySelectorAll("script")[1].remove();
The code above removes the second script tag in a page.

Related

Load and render HTML page using Javascript

I have a unique situation where I need to completely load, run associated scripts, and render an HTML page in the background. This is a full html page.
Here's how I'm currently doing it which isn't working:
I get the page using a GET XHR call and store it as a string in a variable called template. Once I have the string I use JQuery.parseHTML to parse it into an array of elements (including the scripts) and from there filter until I get the element I need, storing it in a variable called content. Then I insert that element into the DOM.
The problem I'm having is that the DOM elements in content are not completely rendered because their scripts haven't been run.
Here's my code:
function (template) {
var jTemplate = $($.parseHTML(template, document, true));
console.log(jTemplate);
var content = jTemplate.filter('.page-wrap').contents()
.filter('#content-wrapper').contents().filter('#content')
.contents().filter('#main-content');
console.log(content);
$("agency-journal-content").replaceWith(content);
}
How can I go about running the scripts and rendering the DOM in the background and then inserting it into the current document or DOM that the user is seeing.

How to display Javascript Variable value to HTML Document

If I use document.write() it clears the whole html document. So how can I take this javascript variable
var beforenoonprice = 6.75;
and have it display to the html document through this div
<div id="beforeNoonCPSlot"></div>
You use the DOM API:
document.getElementById("beforeNoonCPSlot").innerHTML = String(beforenoonprice);
List of DOM API specs.
(In the above, I've explicitly converted the price to a string, but that's just for emphasis; if I hadn't, there would have been an implicit conversion.)
Note that you have to execute that line of code after the element has been created, otherwise we can't find it with document.getElementById. Given that you've said that using document.writeln cleared the whole document, it sounds like you're running your code at a point where the document as a whole has been rendered, so that should be fine.

Define variable before javascript load

I noticed that you can't import a javascript file and define a variable in the same <script>.
This is my problem:
<script type="text/javascript" src="js.js">
var id = "587587";
</script>
Is there a way to load the javascript after the variable without using another <script> tag?
If a script tag has a src attribute, anything between the script tags is ignored. The only way you could do something like this is by dynamically adding a new script tag with an ugly hack like this.
<script type="text/javascript">
var id = "587587";
document.write('<script type="text/javascript" src="js.js"><\/script>');
</script>
Using another script tag before the one with the id would certainly be the preferable and shorter solution.
src
This attribute specifies the URI of an external script; this can be
used as an alternative to embedding a script directly within a
document. script elements with an src attribute specified should not
have a script embedded within its tags.
http://developer.mozilla.org/en-US/docs/Web/HTML/Element/script.html
So, you either have an external script, or you have something inside the <script> tag. You shouldn't have both at once; I'm not sure whether this actually does anything or not.
Use a second script tag.
A script element must either contain script code between the script start and end tags, or reference external script code via the src= attribute. It cannot do both. However, your external code can reference the details of your HTML via the DOM (Document Object Model). So you can treat any HTML element (e.g. a text input field) as a parameter to be passed to your external javascript, where it can be read by e.g. var param = document.getElementById('param').innerHTML;

Targeting an ID that is rendered by a script

I'm using a nifty little script called Tabifier (http://www.barelyfitz.com/projects/tabber/)
Now, long story short, this script, which I run in my head tag, creates a <ul> with <li>s containing <a>s. Also in the head tag it creates IDs for these <a>s. When I inspect the loaded site I can clearly see the ID tags present. However, I cannot call them using getElementById. I've been using
<script>
document.getElementById('rightpanelnav1').style.padding='200px';
</script>
as a sample script in different parts of my code but to no avail. I'm wondering wether it's the placement or order in which these things are defined in my code that's causing it not to recognize the ID. What do you think?
EDIT: I recieved a great answer below, but I still can't get 'rightpanelnav1' to register onclick events...? It's an , there shouldn't be a problem, right? And when I click it, the entire page has been loaded for several seconds...
Firstly, in order to access an element in the DOM, the element must be a part of the DOM (document). So if you place your <script> with getElementById in the page at a place prior to where the element is loaded, it will not see the element in the DOM.
Secondly, it is highly probable that this library you use does its modification on page load, which would mean that no matter where you place your <script> it would have no chance of seeing these elements before running.
As a result, you should have your script wait as well, and do this:
window.onload = function(){
document.getElementById('rightpanelnav1').style.padding='200px';
};
Or for a click event
window.onload = function(){
document.getElementById('rightpanelnav1').onclick = function(){
alert("clicked!");
};
};

How can Javascript in the head access elements in the body?

I often see some JavaScript libraries that are called in the head tag of an html page. However, if these libs call an element in the body tag, there'll be a response (still from the head tag). When I try to call an element from the head, there is no response - why?
Thanks in advance. :)
The browser parses the html page from top to bottom, executing any <script> blocks in place as it finds them. Which means if the JavaScript attempts to access elements on the page it can only see those included higher in the page because the ones lower down have not been parsed yet.
There are two ways to deal with this:
Put your <script> block at the bottom, just before the closing </body> tag (or at least put it after the elements it needs to reference), and/or
Use an onload (or, if you like jQuery, a $(document).ready()) handler.
One way to setup an onload handler is like this:
<head>
<script>
window.onload = function() {
// this function will be called by the browser after
// the entire page has loaded and thus code in the function
// can access any element on the page.
};
</script>
</head>
<body>
... various elements ...
</body>
You may have also seen something like this:
<body onload="someFunction();">
Where someFunction() can be defined in a <script> block in the <head>. It's basically the same thing, but it's so 1990s to do it with an attribute in the html like that. (Actually even the window.onload() is out of date now, but it works and I don't have time to explain the .addEventListener() method.)
That's beacause you propably are trying to call elements before they exist, ie. the HTML isn't parsed yet. To avoid this, you have to wait untill the page is completed, and then execute your script.
To achieve this, you have to assign your function into a onload-event. For example:
<body onload="your_func">

Categories

Resources