I have the following very simple code:
<html>
<head>
<script type="text/javascript" >
function showAlert(){
alert("I am clicked");
}
function one(){
var a1 = [1,2,3];
for (var i=0;i<a1.length;i++) {
var p = document.createElement('p');
p.innerHTML = a1[i];
p.onclick = showAlert;
document.body.appendChild(p);
}
console.log("I am called");
}
one();
</script>
</head>
</html>
I am getting the following error:Uncaught TypeError: Cannot read property 'appendChild' of null. Can anybody tell me, where am I going wrong? I am testing in Chrome.
document.body.appendChild is run before the body is defined, hence document.body is still null.
Either move this script down under the <body></body> or delay it's execution with:
window.addEventListener("load", function () { /* we're ready */ });
document.body.appendChild(p)
In this line. Some days ago I had the same problem.
This happens if you put your script before of the tag body.
<html>
<head>
<script type="text/javascript" >
function showAlert(){
alert("I am clicked");
}
function one(){
var a1 = [1,2,3];
for (var i=0;i<a1.length;i++) {
var p = document.createElement('p');
p.innerHTML = a1[i];
p.onclick = showAlert;
document.body.appendChild(p);
}
console.log("I am called");
}
one();
</script>
</head>
</html>
Will not work.
If you put your function call after the tag it works.
<html>
<head>
<script>
function showAlert(){
alert("I am clicked");
}
function one(){
var a1 = [1,2,3];
for (var i=0;i<a1.length;i++) {
var p = document.createElement('p');
p.innerHTML = a1[i];
p.onclick = showAlert;
document.body.appendChild(p);
}
console.log("I am called");
}
</script>
</head>
<body>
<body>
<script type="text/javascript" >
one();
</script>
</html>
In your context, "body" yet didn't be initialized, so it is null
It looks like you are missing the body tag from your HTML. So document.body is null
Related
The following code snippet creates a new DOM document with a button inside it and adds it to an iframe.
I want to add a JavaScript code inside the new DOM document so that when I click the button id dose something like alert.
I tried the following code but it doesn't work.
<html>
<head>
</head>
<body>
<p><button id="btn" >Click Here</button> to create a new document and insert it below.</p>
<iframe id="theFrame" src="about:blank"></iframe>
<script type="text/javascript">
document.getElementById("btn").onclick = function () {
var frame = document.getElementById("theFrame");
var doc = document.implementation.createHTMLDocument("New Document");
var button = doc.createElement("button");
button.innerHTML = "Alert";
button.setAttribute("id","btn1");
var script = doc.createElement("script");
script.innerHTML = "document.getElementById('btn1').onclick = function() {alert('button clicked!')};";
try {
doc.body.appendChild(button);
} catch(e) {
console.log(e);
}
try {
doc.body.appendChild(script);
} catch(e) {
console.log(e);
}
// Copy the new HTML document into the frame
var destDocument = frame.contentDocument;
var srcNode = doc.documentElement;
var newNode = destDocument.importNode(srcNode, true);
destDocument.replaceChild(newNode, destDocument.documentElement);
}
</script>
</body>
You really don't need to create a new document.
Just get a reference to the document within the frame and do everything within that context.
document.getElementById("btn").onclick = function () {
var frame = document.getElementById("theFrame");
// reference to the iframe document instead of createHTMLDocument
var doc = frame.contentDocument
var button = doc.createElement("button");
button.innerHTML = "Alert";
button.setAttribute("id","btn1");
var script = doc.createElement("script");
script.innerHTML = "document.getElementById('btn1').onclick = function() {alert('button clicked!')};";
try {
doc.body.appendChild(button);
} catch(e) {
console.log(e);
}
try {
doc.body.appendChild(script);
} catch(e) {
console.log(e);
}
}
Plunker demo
My JavaScript object create some HTML elements (two buttons for example) and after user click on these buttons I should call some method of this object. So the question is how I can refer JS object in HTML element to call its method?
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Title Goes Here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function myObj(){
this.a = null;
this.setA = function(a){
this.a = a;
}
this.requestA = function(){
$( "body" ).append($('<input><button onclick="referenceToMyObject.setA($(this).prev().val());">Set A</button>'));
}
return this;
}
</script>
</head>
<body>
<script>
var myObjInst = myObj();
myObjInst.requestA();
</script>
</body>
Creating the event handler inline (onclick="foo()") won’t allow you to reference the object, and is discouraged in any case because you should avoid evaluating strings as code. In addition, your code bypasses JavaScript’s idea of objects somewhat. You can reformulate it as follows:
function MyObj() {
this.a = null;
}
MyObj.prototype.setA = function(a) {
const old = this.a;
this.a = a;
console.log("Updated a from", old, "to", this.a);
};
MyObj.prototype.requestA = function() {
const input = $("<input type='text'>");
const button = $("<button>Set A</button>");
button.click((e) => {
this.setA($(e.target).prev().val());
});
const body = $("body");
body.append(input);
body.append(button);
};
$(document).ready(() => {
const myObjInst = new MyObj();
myObjInst.requestA();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here, we use button.click to define the event handler and new MyObj() to instantiate the object. Apart from that, I cleaned up the code a bit and added a bit of logging so you can see what’s going on.
You could still define setA and requestA within the constructor, as you do in your example. I chose to define them on the prototype since their behaviour is the same across instances.
Try this and please let me know if this works for you.
(working example in JSFiddle https://jsfiddle.net/galeroy/9nocztk4/1/)
<!doctype html>
<html>
<head>
<script>
var myObject = {
createButton: function(){
var p = document.getElementById('par')
var b = document.createElement('button');
b.innerHTML = 'click me';
b.setAttribute('onclick', 'myObject.myMethod()'); // this is the important part
p.appendChild(b);
},
myMethod: function(){
alert("Button created by object, when clicked, calls another method in the same object")
}
}
function init(){
myObject.createButton();
}
</script>
</head>
<body onload="init()">
<p id="par"></p>
</body>
</html>
I would like to change the content of a element with a button click and then have it return back to its original message. How Would i do this preferable with toggle class if possible.
<doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Day Practice</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"> </script>
</head>
<body>
<h1> HotDogs</h1>
<input type=button id=button value=button>
<script>
$("#button").click(function(){
$("h1").html("Change to this");
});
</script>
This changes the header with a button, but I don't know how to revert it when I click on the button again. Maybe Toggle Class, I don't know.
this should solve:
$( "#button" ).toggle(function() {
$("h1").html("Change here");
}, function() {
$("h1").html("Revert back here");
});
Set a flag to toggle and check, and store the old text whenever you change it. An example:
var flag = false;
var old_text = "";
$("#button").click(function () {
if (flag) {
$("h1").html(old_text);
} else {
old_text = $("h1").html();
$("h1").html("Change to this");
}
flag = !flag;
});
You can try this:
var alternate_text = "Change to this";
$("#button").click(function(){
var temp = $("h1").html()
$("h1").html(alternate_text);
alternate_text = temp; // Switch the two instances of text.
});
Since you prefered to do this with toggleClass(), here you go:
$(document).ready(function(){
var oldContent;
$("#button").click(function(){
if($(".newCont")[0]){
$("h1").html(oldContent);
} else {
oldContent = $("h1").html();
$("h1").html("New text here");
}
$("h1").toggleClass("newCont");
});
});
i have this function which i define inside HEAD:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js">
function live() {
$.get("http://mydomain.com/script.php", function(data){
var timer = data;
var elm = document.getElementById("live");
if (timer == 1){
elm.style.display = 'block';
} else{
elm.style.display = 'none';
}
});
}
</script>
and then i do a loop like this at the very end of my document:
<script type="text/javascript">
setInterval(live,10000);
</script>
but i get an error saying live is not defined. Why is that? Could you please tell me what im doing wrong?
Thank you.
Put your code in an separate <script> tag. As soon as a <script> tag has a src attribute, any content of that tag is ignored in favor of the given resource. so just do this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
function live() {
$.get("http://mydomain.com/script.php", function(data){
var timer = data;
var elm = document.getElementById("live");
if (timer == 1){
elm.style.display = 'block';
} else{
elm.style.display = 'none';
}
});
}
</script>
I am trying to create a button in a function declared in an external javascript file. With the html file (in some sense the "main" file), I am trying to access this button and assign click listeners. I am not able to do so. Please see below for the code I have so far.
testDialogJS.js:
/**
* The JS here will be referenced from another file.
*/
function creator() {
console.log("creator.");
var btn = document.createElement("BUTTON");
var text = document.createTextNode("Click me!");
btn.setAttribute("id", "Button");
btn.appendChild(text);
}
testDialog.html:
<html>
<head>
<style>
.hlight{background-color:#ffcc00; }
textarea {
width:100%;
height:100%;
}
</style>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css"/>
<!-- <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.js"></script> -->
<script type="text/javascript" src="testDialogJS.js"></script>
<script type="text/javascript">
window.onload=function() {
console.log("Window has been loaded.");
creator(); //this function is elsewhere.
var btn = document.getElementById("Button");
if(btn == null) {
console.log("Button is null.");
} else {
console.log("Button is not null.");
btn.onclick=function() {
console.log("Hello.");
}
}
}
</script>
</head>
<body>
</body>
</html>
You have not appended your button to the document. So this returns null when you try to select the button using document.getElementById("Button")
Add the following statement in creator() like this
function creator() {
console.log("creator.");
var btn = document.createElement("BUTTON");
var text = document.createTextNode("Click me!");
btn.setAttribute("id", "mybtn");
btn.appendChild(text);
document.body.appendChild(btn);
}
Demo