document.createElement fails for new window - javascript

I have two HTML files, FirstWindow and SecondWindow. FirstWindow has FirstWindowJS.js as its script and SecondWindow has SecondWindowJS.js as its script.
Through FirstWindowJS.js, I open SecondWindow.html. However, I am unable to create an element for it. Here's the code along with the problem -
FirstWindow.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>FirstWindow</title>
</head>
<body>
<script type="text/javascript" src="FirstWindowJS.js"></script>
</body>
</html>
SecondWindow.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>SecondWindow</title>
</head>
<body>
<script type="text/javascript" src="SecondWindowJS.js"></script>
</body>
</html>
FirstWindowJS.js
main();
function main()
{
var myWindow = window.open("SecondWindow.html", "My Window",
"resizable=0,width=700,height=600");
var e = myWindow.document.createElement("currentUserElement");
e.setAttribute("id", "currentUserElement");
e.setAttribute("value","John");
}
SecondWindowJS.js
main();
function main()
{
var e = document.getElementById("currentUserElement");
var value = e.getAttribute("value");
console.log("value = "+value);
}
The error that I get in the SecondWindowJS.js is -
TypeError: e is null
Why is "e" null? What is the mistake?

It's possible that the new window runs its JavaScript before the opener's script continues, but it's more likely that you can't use getElementById on an element that has not been appended to the document yet.
myWindow.document.body.appendChild(e);

You create the element, but it doesn't look like you are adding it to the DOM. An element doesn't exist in the DOM until you explicitly add it using the parentNode.appendChild() method.
In your case it would look something like this, if you just want to add the element as the last element in your body-element:
function main()
{
var myWindow = window.open("SecondWindow.html", "My Window",
"resizable=0,width=700,height=600");
var e = myWindow.document.createElement("currentUserElement");
e.setAttribute("id", "currentUserElement");
e.setAttribute("value","John");
// The element doesn't exist in the DOM until you explicitly add it
myWindow.document.body.appendChild(e);
}

Related

Ask about jquery function operation [duplicate]

This question already has answers here:
How to prevent a click on a '#' link from jumping to top of page?
(24 answers)
Closed 2 years ago.
I'm student and it hasn't been long since I studied programming.
below code is simplified than real for explain.
'test()' is actually Ajax function to get data.
My goal is making 'a tag' for paging operation.
But when i clicked 'a tag', 'test()' inside of '$(document).ready' is called after 'a tag' click event occurred.
So page is always back to 1.
I don't know why this happen.
Anyone could help me?
Thank you!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
var page = 1;
$(document).ready(function(){
test();
alert(page);
});
function test(){
for(var i = 1; i <= 3; i++) {
var a = $("<a></a>").text(i).attr({
href: "",
idx: i
});
a.preventDefault;
$(a).click(function(){
page = $(this).attr("idx");
test();
alert(page);
});
$("#pageLink").append(a," ");
}
}
</script>
</head>
<body>
hello!
<div id="pageLink"></div>
</body>
</html>
For some reason you're calling test() inside of test(). There are a few minor things you need to change also
Prefix jQuery objects with $. var $a=... to avoid ambiguity.
preventDefault is used on the event, not the jQuery object. $a.click(function(event){event.preventDefault();...});
Otherwise it works as I believe you want it to, alerting the page number on click.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
createLinks();
});
function createLinks(){
for(var i = 1; i <= 3; i++) {
var $a = $("<a></a>").text(i).attr({
href: "",
idx: i
});
$a.click(function(event){
event.preventDefault();
page = $(this).attr("idx");
// why are you calling this again? // test();
// maybe you want to load something // loadSomething(page);
alert(page);
});
$("#pageLink").append($a," ");
}
}
</script>
</head>
<body>
hello!
<div id="pageLink"></div>
</body>
</html>

Why I can not get the updated "cars" array in my new popped up window

My index.html has a button(id="my-btn"):
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My INDEX PAGE</title>
</head>
<body>
<br><input type="button" id="my-btn" value="OPEN NEW WINDOW"/>
<script src="js/my.js"></script>
</body>
</html>
above page include my.js which handles button click event, when button clicked, a new browser window will be opened with a new page(test.html)
my.js:
$('#my-btn').click(function(){
window.open('test.html', 'testwindow');
});
The new page (test.html) opened/popped up in new browser window:
test.html:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>TEST</title>
</head>
<body>
<div id="cars"></div>
<script src="js/jquery-1.5.1.js"></script>
<script src="js/mycar.js"></script>
<script src="js/test.js"></script>
</body>
</html>
In the new page, test.js is included which will call functions in MyTest and append the text of number of cars as the content of this pop-up page:
js/test.js
$(document).ready(function(){
MyTest.updateCars(); //MyTest is a function defined in mycar.js
var cars = MyTest.getCars();
$("#cars").append("<strong>number of cars: "+cars.length+"</strong>");
});
Function MyTest is defined in mycar.js:
js/mycar.js
var MyTest = function(){
var cars=[];
var updateCars=function(){
cars.push('car 1', 'car 2');
};
return{
updateCars: function(){
updateCars();
},
getCars: function(){
console.log(cars.length);
return cars;
}
};
}();
But, when the test.html page popped up in a new browswer window, the number of cars is always 0.
As you saw above I have called updateCars() function of mycar.js in test.js but the pop up window does not show the updated cars number , how can I get the updated cars(that's 2 cars, car1 and car2) in the new popped up window?
(I have jquery-1.5.1.js under "js/" directory)
hey i pasted your code in a page and it displayed
number of cars: 2
it seems to work are you just referencing the script wrong?
have you tried the debugger on chrome or firebug?

How to pass Paper.set() to another Javascript in my case?

I have a index.html page, which contains a buttonid="my-btn"
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My INDEX PAGE</title>
</head>
<body>
<div id="my-canvas"></div>
<br><input type="button" id="my-btn" value="OPEN NEW WINDOW"/>
<script src="js/jquery-1.5.1.js"></script>
<script src="js/raphael.js"></script>
<script src="js/my-graph.js"></script>
<script src="js/my.js"></script>
</body>
</html>
js/my.js invoke createCircle function from my-graph.js, and handles button click event, when my-btn button is clicked, a new browser window will be popped up with a new page (test.html)
my.js:
MyTest.createCircle();
$('#my-btn').click(function(){
window.open('test.html', 'testwindow');
});
my-graph.js:
MyTest= function(){
var paper = Raphael("my-canvas", 320, 200);
var st=paper.set();
return {
createCircle: function(){
st.push(
paper.circle(10, 10, 5),
paper.circle(30, 10, 5)
);
}
getSet: function(){
return st;
}
};
}();
The new page(test.html) opened in new browser window:
test.html:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>TEST</title>
</head>
<body>
<div id="my-name"></div>
<script src="js/jquery-1.5.1.js"></script>
<script src="js/my-graph.js"></script>
<script src="js/test.js"></script>
</body>
</html>
In the new page, test.js will be invoked and I want to pass the Paper.set() st from my-graph.js to this test.js and output st.length as the content of this page
js/test.js
$(document).ready(function(){
var st=MyTest.getSet();
$("#my-name").append("<strong>"+st.length+"</strong>");
});
But I always get 0 length of the st in new popped up page. Why?
so your opening a new page with script references to the same code
as the other page
That dosent mean that they have the same state.
The new page will get its own state from evaluating
the script itself
what you can do is save the reference that
var w = window.open('test.html', 'testwindow');
returns you can use that for calling a function on your new page
or you can yost do all the code on the start page with jquery
and useing that window object as your context
var w = window.open('test.html', 'testwindow');
$(w).ready(function() {
$("body", w).append(mystuff);
});
raphael objects are set to a paper i think not shure what will
happend when passing them betwen papers :S

how can you determine location of <script> tag from inside said tag?

I am trying to figure out the location of the script tag the current javascript is running in. What is really going on is that I need to determine from inside a src'd, dynamically inserted javascript file where it is located in the DOM. These are dynamically generated tags; code snippet:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>where am i?</title>
<script type="text/javascript" charset="utf-8">
function byId(id) {
return document.getElementById(id);
}
function create_script(el, code) {
var script = document.createElement("script");
script.type = "text/javascript";
script.text = code;
el.appendChild(script);
}
</script>
</head>
<body>
<div id="find_me_please"></div>
<script>
create_script(byId("find_me_please"), "alert('where is this code located?');");
</script>
</body>
</html>
You could give the script an id tag, like this dude does...
You can use document.write to create a dummy DOM object and use parentNode to escape out. For example:
<script>
(function(r) {
document.write('<span id="'+r+'"></span>');
window.setTimeout(function() {
var here_i_am = document.getElementById(r).parentNode;
... continue processing here ...
});
})('id_' + (Math.random()+'').replace('.','_'));
</script>
This assumes you don't actually have control of the <script> tag itself, such as when it's inside a <script src="where_am_i.js"></script> - if you do have control of the <script> tag, simply put an ID on it, as in:
<script id="here_i_am">...</script>
If you are just running this on page load, this works
<script>
var allScripts = document.getElementsByTagName('script');
var thisScript = allScripts[allScripts.length];
alert(thisScript);
</script>

window.onload != <body onload="">

This is rather interesting, I think. Consider following code, both the window.onload and body onload="" call the same function. However, the results are different. It appears to me that window.onload has a problem with collections. Here's the code:
<html>
<script type="text/javascript">
window.onload = getSpanElements();
function getSpanElements(){
var collectionBoolean = document.getElementsByTagName("span")?true:false;
alert(
"collection exists? " + collectionBoolean + "; number of collection members: " + document.getElementsByTagName("span").length
);
}
</script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<body onload="getSpanElements()">
<span> test </span>
</body>
As you can see, both report that the collection exists, however window.onload reports that it has no members. Any ideas?
You're setting the function wrong:
window.onload = getSpanElements();
should be
window.onload = getSpanElements;
You're setting the onload handler to the return value of getSpanElements() at the moment.
window.onload = getSpanElements();
should be
window.onload = getSpanElements;
The code you have calls the getSpanElements function and assigns its return value as the onload event handler.
You're wrongly doing this:
window.onload = getSpanElements();
which sets the window.onload to the result of the call to the function getSpanElements (undefined).
You should do this instead:
window.onload = getSpanElements;
You might want to move your window.onload assignment below the getSpanElements declaration:
<html>
<script type="text/javascript">
function getSpanElements(){
var collectionBoolean = document.getElementsByTagName("span")?true:false;
alert(
"collection exists? " + collectionBoolean + "; number of collection members: " + document.getElementsByTagName("span").length
);
}
window.onload = getSpanElements;
</script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<body onload="getSpanElements()">
<span> test </span>
</body>
At the point in your code where you're assigning the window.onload event handler, getSpanElements() has not yet been defined. Also, the line should be
window.onload=getSpanElements;
not
window.onload=getSpanElements();
The function name without parentheses is a reference to the function. With parentheses, it executes the function and the return value is assigned to window.onload.
You have to assign a reference to the function getSpanElements to window.onload - currently, the function doesn't get executed onload, but immediately after parsing.
What you actually assign is the undefined return value.
In short: drop the ().
I think the window object is created before any actual elements are parsed.

Categories