innerHTML Cannot Be Set [duplicate] - javascript

This question already has an answer here:
Javascript getElementById null error
(1 answer)
Closed 5 years ago.
Why is the text in the div not changed? What did I do wrong here?
Here's the HTML:
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<div id="demo">Text to be changed.</div>
</body>
</html>
And the Javascript:
document.getElementById("demo").innerHTML = "Hello World";
Thank you in advance.

You need to put the tag at the bottom. Or after the div. When the script is loaded as you have it now, the DOM is not yet ready. So if you run the script after the DOM has been initialized, you'll be fine. So put
<script src="script.js"></script>
Just before </body>

Your script is runing before your document is finished loading, so you may need to wait for onload. With jQuery you'd do this:
$(function() {
document.getElementById("demo").innerHTML = "Hello World";
});
Or more succinctly:
$(function() {
$("#demo").html("Hello World");
});

You need to wrap your JavaScript with a listener for the DOM being ready:
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("demo").innerHTML = "Hello World";
});
It's firing too early at the moment.
https://developer.mozilla.org/en/docs/Web/Events/DOMContentLoaded

this is working
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
document.getElementById('demo').innerHTML = 'Hello World';
});
</script>
</head>
<body>
<div id="demo">Text to be changed.</div>
</body>
</html>

Related

How to fire up a code when changes happens on another document?

As in the question I'm trying to fire up a code when a event happens, in my case I got the following index.html code:
<html>
<body>
<script>
window.addEventListener('storage', function(event) {
console.log("changed key: " + event.key);
console.log("old value : " + event.newValue);
});
</script>
</body>
</html>
And here I'm trying to put a item in the localStorage to trigger the javascript code from index.html:
<html>
<body>
<script>
window.localStorage.setItem("sss", "test");
console.log(window.localStorage.getItem("sss"));
</script>
</body>
</html>
Couldn't get the output working unfortunately, any ideas?

Undefined when doing document.write() with button OnClick="counter"

I'm new to programming and would need some help, why the document.write() didn't work and basically the page crashes... Can anyone help me?
<!DOCTYPE html>
<html>
<head>
</head>
<script type="text/javascript">
function showText() {
var x;
var counter;
if ( x === 0) {
counter = 0;
x = 1;
}
counter = counter + 1;
document.write("Times clicked: " + counter);
}
</script>
<body>
<script type="text/javascript">
showText();
</script>
<button onclick="showText();">Click Me!<button>
</body>
</html>
Avoid using document.write
Quoting from the MDN Developer Network documentation page:
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open which will clear the document.
So basically, your issue is using document.write after the page has loaded: this will result in deleting the entire content of the page and displaying that string.
Also, your code doesn't work because your count variable is declared inside the showText function, and you're trying to access it outside of it, running into an error.
Solution
To make your code work you should create another element, let's say a <p> element, and display the text inside of it. Here's an example of a correct page:
<!DOCTYPE html>
<html>
<head></head>
<body>
<button id="btn">Click me!</button>
<p id="txt">Times clicked: 0</p>
<script type="text/javascript">
function showText() {
count++;
text.textContent = "Times clicked: " + count;
}
var count = 0,
button = document.getElementById("btn"),
text = document.getElementById("txt");
button.addEventListener("click", showText);
</script>
</body>
</html>
Check out a live demo here.

Cannot get html content after a load

I'm trying to replace the context of a loaded element with the following code:
$("#menu1").load("./templates/menu.html");
var str = $("#menu1").html();
alert(str);
str.replace("[number]", "1");
$("#menu1").replaceWith(str);
But I always get an empty str, the menu1 gets loaded correctly with the menu.html content so I have no idea what's going on.
You need to test the string after the load - the way you have done it, it can be run whilst the load is still going. Try this:
$("#menu1").load("./templates/menu.html", function() {
var str = $("#menu1").html();
alert(str);
str.replace("[number]", "1");
$("#menu1").replaceWith(str);
});
More information
$("#menu1").load("./templates/menu.html", function(){
//complete
var str = $("#menu1").html();
});
Loading part isn't instant so you are trying to apply var str = $("#menu1").html(); before load() has time to complete
You need to do the task in callback function of load:-
For example :-)
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#*" data-semver="2.1.3" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
Hello this is rachit 1 1 1 1.
<div id="menu1"></div>
<script>
$("#menu1").load("index.html", function() {
var str = $("#menu1").html();
alert(str);
str.replace("[number]", "1");
$("#menu1").replaceWith(str);
});
</script>
</body>
</html>
Plunker

What's wrong with this short Javascript code?

I'm trying to make the short Javascript code throw an alert and show 93 instead of 0-93 but it's not working ?
<html>
<head>
<script type="text/javascript">
function numberFromInput(value) {
return alert(Number(value.match(/[-]?(\d*)$/).pop()));
}
</script>
</head>
<body>
numberFromInput(0-93);
</body>
</html>
You have to call the function (you're just displaying its call code as content). And you have to pass the value as a string (you need quotes around 0-93):
<script type="text/javascript">
function numberFromInput(value) {
return alert(Number(value.match(/[-]?(\d*)$/).pop()));
}
numberFromInput("0-93");
</script>

what if jquery.js is include into the page twice?

If I introduce the jquery.js into the page twice(unintentional OR intentional), what will happen?
Is there any mechanism in jquery that can handle this situation?
AFAIK, the later one jquery will overwrite the previous one, and if there is some action binding with the previous one, it will be cleared.
What can I do to avoid the later one overwrite the previous one?
===edited===
I couldn't understand WHY this question got a down vote. Could the people who give the down vote give out the answer?
==edited again==
#user568458
u r right, now it's the test code:
<html>
<head>
</head>
<body>
fast<em id="fast"></em><br>
slow<em id="slow"></em><br>
<em id="locker"></em>
</body>
<script type="text/javascript">
function callback(type){
document.getElementById(type).innerHTML=" loaded!";
console.log($.foo);
console.log($);
console.log($.foo);
$("#locker").html(type);
console.log($("#locker").click);
$("#locker").click(function(){console.log(type);});
$.foo = "fast";
console.log($.foo);
}
function ajax(url, type){
var JSONP = document.createElement('script');
JSONP.type = "text/javascript";
JSONP.src = url+"?callback=callback"+type;
JSONP.async = JSONP.async;
JSONP.onload=function(){
callback(type);
}
document.getElementsByTagName('head')[0].appendChild(JSONP);
}
</script>
<script>
ajax("http://foo.com/jquery.fast.js", "fast");
ajax("http://foo.com/jquery.slow.js", "slow");
</script>
</html>
it produced the result:
undefined test:12
function (a,b){return new e.fn.init(a,b,h)} test:13
undefined test:14
function (a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)} test:16
fast test:19
undefined test:12
function (a,b){return new e.fn.init(a,b,h)} test:13
undefined test:14
function (a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)} test:16
fast
the token "$" of the previous one(jquery.fast.js) is overwrite by the later(jquery.slow.js) one.
Is there any method to avoid the overwriting?
I did try this code:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function() {
$('#try').click(function() {
alert('ok');
});
});
</script>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<button id="try">Try me</button>
</body>
</html>
Nothing happend. On click I've got an alert. Same result if the second jquery.js loaded in body tag before or after the button.

Categories

Resources