remove element <script> in body - javascript

I got a script converter like this
var currency_data='USD,0.712497,0.01|AUD,0.5576,0.05|AED,0.194009,0.25|BRL,0.248647,0.01|JPY,0.00594888,1|GBP,1.09482,0.01|CAD,0.572195,0.01|CNY,0.115772,0.5|EUR,0.795717,0.01|INR,0.0115219,0.1|ILS,0.178705,0.01|QAR,0.195741,1|RUB,0.0114246,0.01|SAR,0.189999,1|SGD,0.522129,0.01|THB,0.0220219,0.25';
var currency_sdrPer=new Array(),currency_Unit=new Array();currency_make_arrays();function currency_make_arrays(){var d=currency_data.split("|");for(var e=0;e<d.length;e++){var b=d[e].split(","),f=b[0];currency_sdrPer[f]=b[1];currency_Unit[f]=b[2]}};
function currency_rnd(h,e){h=Math.round(h/e)*e+".";var g=(e+".").split("."),c=h.split("."),b=c[1],a=g[1].length,d=b.length;if(d>a){b=b.substring(0,a)}for(var f=0;f<a-d;f++){b+="0"}return c[0]+(a==0?"":"."+b)}function currency_convert(f,d,c){var e=currency_sdrPer;if(!e[d]||!e[c]){return""}return currency_format(f*(e[d]/e[c]),currency_Unit[c])}function currency_format(c,f){var g=typeof currency_thousandsSeparator=="string"?currency_thousandsSeparator:",",b=typeof currency_decimalSeparator=="string"?currency_decimalSeparator:".",f=(typeof currency_decimalDigits=="number")?(1/Math.pow(10,currency_decimalDigits)):(typeof f=="number"?f:0.01),j=typeof currency_thousandsSeparatorMin=="number"?currency_thousandsSeparatorMin:3;if(typeof currency_round=="boolean"&&currency_round){c=currency_rnd(c,f)}var i=(""+c).split("."),h=i[0],e=i.length>1?b+i[1]:"",a=/(\d+)(\d{3})/;if(g!=""){while(a.test(h)&&h.length>j){h=h.replace(a,"$1"+g+"$2")}}return h+e};
function conversion(e,d,c){document.write(currency_convert(e,d,c))}function currency_getRateHTML(d,c){var g=currency_convert(1,d,c);if(g==""){return""}var f=d+"_"+c+".html";if(c<d){f=c+"_"+d+".html"}f="http://coinmill.com/"+f;var e=unescape("%3Ca+href%3D%22%24link%22%3E%24from_the_name+is+worth+%3Cb%3E%24rate%3C/b%3E+%24to_plural_name%3C/a%3E%3Cbr%3E");if(typeof currency_template!="undefined"){e=currency_template}return e.replace("$link",f).replace("$rate",g).replace("$from_abbrev",d).replace("$from_name",d).replace("$from_plural_name",d+"s").replace("$from_the_name","the "+d).replace("$to_abbrev",c).replace("$to_name",c).replace("$to_plural_name",c+"s").replace("$to_the_name","the "+c)}function currency_showRate(d,c){document.write(currency_getRateHTML(d,c))}function currency_showRates(){for(var e=0;e<currency_rate_list.length;e++){var d=currency_rate_list[e];e++;if(e<currency_rate_list.length){var c=currency_rate_list[e];currency_showRate(d,c)}}}if(typeof currency_rate_list!="undefined"){currency_showRates()};
after element <head>
<script>
var currency_round=true;
</script>
and the calling inside after <body>:
<div>USD 60.61 = GBP <script>conversion(60.61,"USD","GBP");</script></div>
however, I really mind that there are <script> and </script> element inside body where as it's not good for html validation.
Is there any way to change it to be or element?

If you really want to move it out of the body (and there doesn't seem to be any point in doing so, it isn't invalid to have a script there) then you will need to:
Create an element in the body to put the content in
Replace all the document.write statements with DOM methods
Call the conversion function after the element becomes available (e.g. with an load event handler)

I think there is no other way to use.
so use script within body.

Related

Placeholder for double and single quotes

I have a function which returns a table of given size containing given content in each cell displaying it in the div with the given ID.
generate_table(4,4,'Cell Content','display')
To test this function I have used onload on my body tag. The function does work. However i wish to have an input of type number inside the cells so
<body onload="generate_table(4,4,'<input type='number'>','display')">
The problem, if you did not see it is that the string that I am passing as the content of the cells gets cut at the ' before number.
Escape the characters:
<body onload="generate_table(4,4,'<input type=\"number\">','display')">
Or call the function from a JavaScript file or even embed it in your HTML file:
<html>
...
<script>
document.querySelector('body').addEventListener('load', function() {
generate_table(4,4,'<input type="number">','display')
}, false);
</script>
Don't use inline handlers. Add a listener properly using JavaScript instead, and you won't have to worry about any escaping issues.
<body>
and, in the JavaScript:
document.body.addEventListener('load', () => generate_table(4,4,'Cell Content','display'));

Getting DOM element information from javascript

So I'm trying to grab some attributes of a div table from the DOM from within a script - and failing.
Code should speak for itself:
<head>
<script type = "text/javascript" src = "SCRIPT_IN_QUESTION.js"></script>
</head>
<body>
<div id = "my_elements">
<!-- I want to access 'attribute-one' data attributes from
all children -->
<div data-attribute-one = "Hello"></div>
<div data-attribute-one = "World"></div>
</div>
</body>
I've seen how this is done with an embedded script in the DOM using something along the lines of:
<script type = "text/javascript">
var values = document.getElementById('my_elements').childNodes;
var foo = values[0].getAttribute('data-attribute-one');
</script>
I'm trying to access these attributes from within a script that isn't embedded into the DOM, and getAttribute is undefined - guess you can only ue that within the DOM.
How do I access this data in a script 'outside' the DOM?
As the below comment states, doing this after the DOM has been loaded makes sense to do, and I'm doing it something like:
window.addEventListener('load', onload, false);
function onload(){
var data = document.getElementById('canvas_segments').childNodes;
//This throws an undefined error
var attribute = data[0].getAttribute('data-attribute-one');
}
Many thanks
Use .children instead of .childNodes (which also includes text nodes). And you may need to wrap your call into onload event, e.g.
<body onload="onLoad()";>
<div id = "my_elements">
<!-- I want to access 'attribute-one' data attributes from
all children -->
<div data-attribute-one = "Hello"></div>
<div data-attribute-one = "World"></div>
</div>
</body>
and in your script:
function onLoad() {
var values = document.getElementById('my_elements').children;
var foo = values[0].getAttribute('data-attribute-one');
}
You have a timing issue here. The script in question is being executed before the DOM is complete, so there is no element.
Either you can move the script tag to the bottom of the page, after all other markup, or you can put the code in a window.onload function.
First of all in the code snippet above, you are attaching the javascript before the DOM structure is loaded. Attach the js file after body so that the HTML content gets loaded first and then the js executes.
After you have done this you will still hit an issue saying, 'Uncaught TypeError: undefined is not a function.' This will be because you are using 'ChildNodes' instead of 'Children.' The difference between the two is that Children gets only Elements whereas 'ChildNodes' will fetch nodes too. Refer this question for a clearer distinction between the two (What is the difference between children and childNodes in JavaScript?)
You might be interested in a working copy of your code: http://goo.gl/HonxtJ

Deleting and inserting Code in a DIV via jQuery

I know this has been adressed before, but I can't seem to get it working for me.
I am trying to create a football pitch with editable players via HTML/JavaScript/jQuery.
I can produce the field the first time when loading the page without any problems. The code looks like this:
<div id="pitch" class="updateAble">
<script type="text/javascript">
appBuilder(team1, team2);
</script></div>
appBuilder() looks like this:
var appBuilder = function (team1, team2) {
team1.Display();
team2.Display(); }
It simply creates the players on the pitch for both teams. As it does. I now want to push an input-button to call a function appUpdate(), which deletes the content of #pitch and puts the appBuilder()-part in again as to renew it (if I changed or added players):
var appUpdate = function () {
var newContent = "<script type='text/javascript'>appBuilder(team1, team2);</script>";
var updateItem = $('#pitch');
updateItem.empty();
updateItem.append(newContent);}
Here is what drives me nuts: It seems to work just fine up to and including the empty()-function. So the code has to be fine.
But when I try to append newContent to the #pitch-DIV, the programm seems to completely delete everything inside <head> and <body> it recreates a clean html-file (with empty html-, head-, body-tags) and inserts my players inside <body>.
Any ideas as to why it is doing that?
Thanks in advance!
UPADTE: The solution was a rookie mistake (which is fitting, since I'm a rookie). The Team.Display()-method was trying to do a document.write() call. As I learned: If you call document.write once the document is fully loaded, it will delete your site. Thanks to jfriend for the solution! :)
If you call document.write() AFTER the document has finished loading, then it will clear the current document and create a new empty one.
What you need to do is use DOM insertion operations rather than document.write() to add/change content in the DOM once the document has already loaded.
My guess is that the .Display() method is using document.write() and you need to change the way it works to insert content into a parent node rather than write it into the current position.
Some ways to insert content:
var newNode = document.createElement("div");
node.appendChild(newNode);
node.innerHTML = "<div>My Content</div>";
Or, if you're using jQuery, you can use it's wrappers for this:
obj.append("<div>My Content</div>");
obj.html("<div>My Content</div>");
.html() would empty and fill the div at once. Have you tried that ?
updateItem.html(newContent);
I proposed a JQuery replacement for your code that does what you want, ion the style of your own typing.
Note that I kept the .html() call to mimic your "empty()" function, but it is not necessary. Simply put he code in the append, straight into the html() et get rid of the extra unnecessary remaing bit of code.
My code replacement, as a 100% functioning .html file. Hope it helps, cheers.
<html>
<header>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var appBuilder = function (team1, team2) {
//team1.Display();
//team2.Display();
}
var team1, team2;
</script>
</header>
<body>
<div id="pitch" class="updateAble">
<script type="text/javascript">
appBuilder(team1, team2); // Original code to be updated
</script>
</div>
<script>
var appUpdate = function () {
$("#pitch").html("<!-- Old javscript code has been flushed -->").append($("<script />", {
html: "appBuilder(team1, team2); // brand new, replaced code"
}));
}
appUpdate();
</script>
</body>
</html>

Why does appendChild only work when I remove the docType

When I put any sort of doctype declaration like <!DOCTYPE html >, appendChild does not work.... Why?
<form>
<script language="javascript">
function function2() {
var myElement = document.createElement('<div style="width:600; height:200;background-color:blue;">www.java2s.com</div>');
document.forms[0].appendChild(myElement);
}
</script>
<button onclick="function2();"></button>
</form>
I'm trying to get data from a popup window's parent opener...is that possible? The data can be a string literal or value tied to the DOM using jQuery .data()
If you're having this problem in IE, it's probably because the presence of a DOCTYPE declaration forces the browser into "standards-compliance" mode. This can cause code that doesn't conform to expected standards to break.
In your case, it's probably because document.createElement doesn't accept an HTML fragment - it accepts an element name, e.g. document.createElement('div').
Try replacing your function body with something like this:
var myElement = document.createElement('div');
myElement.style.width = '600px';
myElement.style.height = '200px';
myElement.style.backgroundColor = 'blue';
myElement.appendChild(document.createTextNode('www.java2s.com'));
document.forms[0].appendChild(myElement);
Read up on the document object model here: https://developer.mozilla.org/en/DOM
Also, jQuery is good for easily creating elements using the syntax you specified.

getting the contents of a function in an `onclick` attribute in my html with jQuery

What?! I know, what a bad idea.
Firstly I have no control over the html that was output, its from a vendor and it is produced via their crazy system that our company has an agreement with. (let's not talk about the situation, I know it's not optimal)
In the html I have:
<a id="notify" onclick="location.href='index.php?foo=bar';return false;" href="javascript:;">Notify!</a>
In my JS If I do:
console.log($("#notify").attr("onclick"))
I recive:
onclick(event)
Which makes sense, but I need to change the onclick's attribute, so it reads to something like:
onclick="location.href='index.php?foo=bar&zoobazz=moo';return false;"
better yet, if I could remove the onclick and replace the href attributes value with location.href.
This will give you the function in a string
$("#notify").attr("onclick").toString()
Grep the URL after that
If I understand your question correctly, you want to actually see what the onclick event is doing and append to it, not just replace it. I tried this in chrome and it works, but it's pretty much a hack. Basically, when you get a reference to the "click" or "onclick" event function (using either jQuery or pure JS), then you can to a ".toString()" on it to convert the function into a string. Then you just strip off the "function" definition using some trickery and you're left with what you need - "location.href='.......".
Then just append your additional parameters. Hopefully this leads you in the right direction.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
var $target = $("#notify");
var funcBody = $target.attr("onclick").toString().split("\n")[1].split(";")[0];
$target.attr("onclick","").attr("href", funcBody);
});
</script>
</head>
<body>
<a id="notify" onclick="location.href='index.php?foo=bar';return false;" href="javascript:;">Notify!</a>
</body>
</html>
document.getElementById('notify').onclick = function() {location.href='index.php?foo=bar&zoobazz=moo';return false;};
Does
$("#notify").click(function() { $("#notify").attr("onclick", "location.href='index.php?foo=bar&zoobazz=moo';"); return false;})
not do what you need it to do?
You can set onclick by using $("#foo").click = '';
You can change href by changing the attribute, using .attr(key, value);
http://docs.jquery.com/Attributes, and http://docs.jquery.com/Tutorials:Edit_in_Place_with_Ajax
so
$('#foo').click = '';
$('#foo').attr('href', 'whateveryousetitto');
I may be reading too much into the question, but I think OP is asking how to get the event code so that it can be manipulated, not just replaced. When specifying "index.php?foo=bar", I don't think the value of bar is known. If this was a known value, then why read the onclick value at all?
alert($('#notify').click);
?

Categories

Resources