I'm trying to make a money display for a form which I am making, now I found this script on the web: http://jsfiddle.net/QQGfc/ And I'm trying to implement it into my code like this: (but it's not displaying the text.)
</script>
<script type="text/javascript">
document.getElementById("MyEdit").innerHTML = "My new text!";
</script>
With this in the body
<?php
include'includes/header.php';
include'includes/slider.php'; //carousel
?>
<h2>Contact Information</h2>
<div id="MyEdit">
This text will change
</div>
Ay idea whats going wrong?
You imply that the JavaScript is in the <head>.
When it runs, the <body> hasn't been parsed, so the element you are trying to modify does not exist.
Either:
Move the script to after the <div> you are trying to modify.
Wrap the script in a function and call that function after the <div> exists (e.g. by binding it as a load event handler).
you should do it after the DOM is completely loaded:
<script type="text/javascript">
window.addEventListener("load", function(){
document.getElementById("MyEdit").innerHTML = "My new text!";
});
</script>
Related
I'm learning javascript and studying this example:
<html>
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML="New text!";
</script>
</body>
</html>
My question is why doesn't the script work properly when the line with <p id="p1">Hello World!</p> is below the script, and what happens during its execution? Thank you.
Because the JavaScript is run when the browser encounters it, when compiling/rendering the page; not once it's finished rendering the page. So, if the element appears after the script it doesn't (yet) exist at the point at which the JavaScript is run.
You could, though, create a function and have that function run once an element has loaded, for example:
<script>
function bodyLoaded(){
document.getElementById('p1').innerHTML = 'New text!';
}
</script>
<body onload="bodyLoaded()">
<!-- HTML here... -->
<p id="p1"></p>
</body>
Javascript is an interpreted language. 'interpreted' means that it:
"executes instructions directly, without previously compiling a
program into machine-language instructions"
Hence because the javascript interpreter executes instructions on the page line by line (starting from the top of the page), the order in which code is defined is crucial. So in your example the paragraph element has to be defined before your call to getElementById.
Elements must be defined in order for JavaScript to recognize them. If you chose to put your JavaScript inside the <head> tag, then you can do this with the window.onload event. This can be done several ways.
//Obtrusive JavaScript
<html>
<head>
<script>
function loadMe(){
var doc = document;
function E(e){
return doc.getElementById(e);
}
E('p1').innerHTML = 'New text!';
}
</script>
</head>
<body onload='loadMe'>
<p id='p1'>Hello World!</p>
</body>
</html>
/* Unobtrusive JavaScript ---> the way you should learn it in my opinion
Notice there's no onload attribute in the body tag. Also, I use onload
instead of window.onload, because window is implicit, just as document
is a property of window as well.
*/
<html>
<head>
<script>
onload = function(){
var doc = document;
function E(e){
return doc.getElementById(e);
}
E('p1').innerHTML = 'New text!';
}
</script>
</head>
<body>
<p id='p1'>Hello World!</p>
</body>
</html>
Of course, you should use external JavaScript whenever possible.
I'm sure this is a fairly basic question, but I'm relatively new to jQuery so was hoping someone might be able to help.
Basically, I need to load an HTML snippet into a page. This works fine when the snippet contains just HTML, but not when it contains a script.
I've stripped down my code to the bare minimum for clarity. This is index.html:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<h1>Heading</h1>
<div id="banner"></div>
<script>
$(document).ready(function(){
$('#banner').load('banner.html');
});
</script>
</body>
</html>
And banner.html contains just the following (as an example):
<h2>Subheading</h2>
<script>
document.write('Hello');
</script>
The script is executed, but for some reason it strips out the rest of the HTML in both index.html and banner.html (i.e. it just displays "Hello" and nothing else).
Any help greatly appreciated!
document.write after the page has load writes to the document, and at the same overwrites everything else currently in the document, that's why you end up with only the string "hello".
Just remove the document write :
<h2>Subheading</h2>
<p id="test"></p>
<script>
document.getElementById('test').innerHTML = 'hello';
</script>
that is becuase when banner.html is loaded .. the script inside banner.html get executed, which writes "hello" in your document(the document here is your entire index.html)
one way to understand this is by replacing certain content of banner.html rather than the whole document.
banner.html
<h2>Subheading</h2>
<div id="divID"></div>
<script>
$('#divID').html('hello'); //using jquery .. gets the element with id as divID and replace the HTML
</script>
here i am replacing just the div whose id is "divID" rather than replacing the enrite document
I have a script in an HTML page of the following:
<script id="scriptid" type="text/html">
<div id="insidedivid">
... html code ...
</div>
</script>
I am able to get the HTMLScriptElement using $("#scriptid") but I am not able to get the underlying div object with the id "insidedivid". Whats the way to do it?
It's not possible; the browser does not treat HTML content inside of <script> tags as part of the DOM. When you retrieve the content of the <script> tag with $('#idhere').html(), you're getting a string result.
To answer Troy's question, he's most likely including templates in the <head> of his document so he can ultimately render content dynamically on the browser-side. However, if that is the case, the OP should use a different MIME type than text/html. You should use an unknown MIME type such as text/templates--using text/html confuses what the purpose of the content is.
I'm guessing the reason you're trying to reach into the <script> tag and grab a div is because you've built smaller sub-templates within the single <script> tag. Those smaller templates should rather be placed into their own <script></script> tags rather than contained in one large <script></script> tag pair.
So, instead of:
<script type="text/template" id="big_template">
<div id="sub_template_1">
<span>hello world 1!</span>
</div>
<div id="sub_template_2">
<span>hello world 2!</span>
</div>
</script>
Do this:
<script type="text/template" id="template_1">
<span>hello world 1!</span>
</script>
<script type="text/template" id="template_2">
<span>hello world 2!</span>
</script>
I think it's perfectly valid to have a div inside a script tag (or at
least useful), if a div makes sense to the TYPE you defined for the
script. For example, John Resig uses a script tag with type "text/
html" in his micro-templating solution:
http://ejohn.org/blog/javascript-micro-templating/
In this instance though (and in reply to the original author) you add
an ID to the SCRIPT tag, and refer to that (I don't see why it
wouldn't work with that facebook type instead of html - but you'd
probably want to test it in a few different browsers ;). For the
example you gave, you can get a reference to the DIV by doing:
<script id="scriptid" type="text/html">
<div id="insidedivid">
... html code ...
</div>
</script>
$(function(){
alert($( $( '#scriptid' ).html() ).text() ); //alerts " ... html code ..."
});
The "trick" is to get the HTML of the script tag and turn in into DOM
elements with jQuery - but remember, because you are passing all the
HTML into the jQUery function then you are immediately selecting ALL
of the top level elements. In this case, there is just one DIV - so
you are just selecting that.
Your HTML is invalid. HTML Validator.
If you want to have HTML you can get just like that, use something like this:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<title></title>
<script type="text/javascript" src="//code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var msg1 = $('message1');
// Execute code here
});
</script>
</head>
<body>
<div id="content">Content</div>
<div id="hidden" style="display: none">
<div id="message1">Message 1</div>
<div id="message2">Message 2</div>
</div>
</body>
</html>
If you are making a templating system, you may want to use AJAX instead.
I want to add a javascript google ad but I can't insert the javascript into the div using jquery. I try to simulate my problem with this test, which is using some advice I found on stackoverflow , but it does not work.
I want <script type='text/javascript'>document.write('hello world');</script> to be inserted in the div, and "hello world" be displayed between the tag_1 and tag_2.
Here is the code :
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var str="<script type='text/javascript'>document.write('hello world');";
str+="<";
str+="/script>";
$('#insert_here').append(str);
});
</script>
</head>
<body>
tag_1<br/>
<div id="insert_here">
</div>
tag_2<br/>
</body>
</html>
Tanks for your answers,
Lucas
See my answer to Are dynamically inserted <script> tags meant to work? for why you can't use innerHTML, which jQuery's functions map to when passed a HTML string, to insert a script element. document.write will also fail when used after the document has been fully parsed.
To work around this, you will have to use DOM functions to insert an element into the div. Google ads are iframes, so it's usually a case of finding the iframe code and appending that instead.
To correctly insert a script element, you need to use DOM functions, for instance:
var txt = 'alert("Hello");';
var scr = document.createElement("script");
scr.type= "text/javascript";
// We have to use .text for IE, .textContent for standards compliance.
if ("textContent" in scr)
scr.textContent = txt;
else
scr.text = txt;
// Finally, insert the script element into the div
document.getElementById("insert_here").appendChild(scr);
I figured out a great solution:
Insert your Google Adsense code anywhere on your page - e.g. if your CMS only allows you to put this on the right hand side then stick it there.
Wrap a div around it with display:none style
Add some jquery code to move the div to the location you desire.
Since the javascript has already run there is no problem then with moving the block of script to wherever you'd like it to be.
e.g. if you wish to put 2 blocks of google adverts interspersed throughout your blog (say after paragraph 1 and after paragraph 4) then this is perfect.
Here's some example code:
<div id="advert1" style="display:none">
<div class="advertbox advertfont">
<div style="float:right;">
<script type="text/javascript"><!--
google_ad_client = "pub-xxxxxxxxxxxxxxxxx";
/* Video box */
google_ad_slot = "xxxxxxxxxxxxxxxxx"
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('#advert1').appendTo("#content p:eq(1)");
$('#advert1').css("display", "block");
});
</script>
p.s. #content happens to be where the content starts on my CMS (Squarespace) so you can replace that with whatever you have in your CMS. This works a treat and doesn't break Google ToS.
You cannot use document.write after the page has finished loading. Instead, simply insert the contents that you want to be written in.
<script type="text/javascript">
$(function() { // This is equivalent to document.ready
var str="hello world";
$('#insert_here').append(str);
});
</script>
I'm trying to write a javascript function that adds some DOM nodes to the document in the place it was called, like this:
...
<div>
<script type="text/javascript">
pushStuffToDOMHere(args);
</script>
</div>
...
i try to do it 'cleanly', without using node id property of the div, or innerHTML string manipulation. for that I need to know where in the document the script tag is located.
is there a way to do it?
Talking about cleanly, I don't think your approach is particularly clean. It is a much better idea to give the div a unique id and execute your javascript when the DocumentReady-event fires.
Do you have an overriding reason for doing it this way? If not the suggestion to use a unique id makes the most sense. And you can always use a library like jQuery to make this even easier for yourself.
However, the following quick test shows that if you use document.write() in the function then it writes the value into the place where the function was called from.
<html>
<head>
<script type="text/javascript">
function dosomething(arg){
document.write(arg);
}
</script>
</head>
<body>
<div>The first Div</div>
<div>The
<script type="text/javascript">
dosomething("Second");
</script>
Div
</div>
<div>The
<script type="text/javascript">
dosomething("Third");
</script>
Div
</div>
</body>
</html>
But, again the question, are you sure this is what you want to do?
Although I agree with n3rd and voted him up, I understand what you are saying that you have a specific challenge where you cannot add an id to the html divisions, unless by script.
So this would be my suggestion for inlining a script aware of its place in the DOM hierarchy, in that case:
Add an id to your script tag. (Yes, script tags can have ids, too.)
ex. <script id="specialagent" type="text/javascript">
Add one line to your inline script function that gets the script element by id.
ex. this.script = document.getElementById('specialagent');
...And another that gets the script element's parentNode.
ex. var targetEl = this.script.parentNode;
Consider restructuring your function to a self-executioning function, if you can.
Ideally it executes immediately, without the necessity for an 'onload' call.
see summary example, next.
SUMMARY EXAMPLE:
<script id="specialagent" type="text/javascript">
var callMe = function(arg1,arg2,arg3) {
this.script = document.getElementById('specialagent');
var targetEl = this.script.parentNode.nodeName=="DIV" && this.script.parentNode;
//...your node manipulation here...
}('arg1','arg2','arg3');
</script>
The following TEST code, when run, proves that the function has identified its place in the DOM, and, importantly, its parentNode. The test has division nodes with an id, only for the purpose of the test. They are not necessary for the function to identify them, other than for testing.
TEST CODE:
<html>
<head>
<title>Test In place node creation with JS</title>
</head>
<body>
<div id="one">
<h2>Child of one</h2>
<div id="two">
<h2>Child of two</h2>
<script id="specialagent" type="text/javascript">
var callMe = function(arg1,arg2,arg3) {
this.script = document.getElementById('specialagent');
var targetEl = this.script.parentNode;
/*BEGIN TEST*/
alert('this.script.id: ' + this.script.id);
alert('targetEl.nodeName: ' + targetEl.nodeName + '\ntargetEl.id: '+targetEl.id);
alert('targetEl.childNodes.length: ' + targetEl.childNodes.length);
var i = 0;
while (i < targetEl.childNodes.length) {
alert('targetEl.childNodes.'+i+'.nodeName = ' + targetEl.childNodes[i].nodeName);
++i;
}
/*END TEST - delete when done*/
//...rest of your code here...to manipulate nodes
}('arg1','arg2','etc');
</script>
</div>
</div>
</body>
</html>
Not really sure what your trying to achieve but this would pass the dom element to the function when clicked. You could then use jquery in the function to do what you wanted like so
...
<script type="text/javascript">
function pushStuffToDOMHere(element)
{
$(element).append("<p>Hello</p>"); // or whatever
}
</script>
<div onclick="pushStuffToDOMHere(this);">
</div>
...
my solution is a compbination of the (good) answers posted here:
as the function is called, it will document.write a div with a unique id.
then on document.onload that div's parent node can be easily located and appended new children.
I chose this approach because some unique restrictions: I'm not allowed to touch the HTML code other than adding script elements. really, ask my boss...
another approach that later came to mind:
function whereMI(node){
return (node.nodeName=='SCRIPT')? node : whereMI(node.lastChild);
}
var scriptNode = whereMI(document);
although, this should fail when things like fireBug append themselves as the last element in the HTML node before document is done loading.