JavaScript --- Looping through elements in webpage #2 from webpage #1 - javascript

Totally new to JavaScript. As in, today.
From an .html file on my MacBook desktop, I want to open TWO webpages. The first is the file itself, say from the command line, as follows:
open ~/Desktop/first.html
The second webpage is one that I call from the first.html file:
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<title>JavaScript stuff</title>
</head>
<body>
<script>
w = window.open('https://fireship.io/courses/javascript/beginner-js-where-to-run/');
const elements = w.document.querySelectorAll('*');
const count = elements.length;
alert(count)
elements.forEach((elem) => {
console.log(elem)
});
</script>
</body>
</html>
WHAT I WANT TO BE HAPPENING is that w.document.querySelectorAll('*') is getting all elements in the second webpage, meaning https://fireship.io/courses/javascript/beginner-js-where-to-run/. WHAT'S ACTUALLY HAPPENING, though, is that the elements from first.html are returning. This is confirmed by inspecting the console output of first.html.
So, my general question is --- How do I loop through the elements of one webpage from scripting that resides in another?
Any help or direction is much appreciated!
Justin

Related

Link two JavaScript files to work together on top of an HTML page

I have homework for my programming class which requires that I work with JS classes. On top of that, I have to work with HTML and the classes have to be defined on a separate .js file. I've done all the work, and it runs ok if the classes are defined on the same .js file, but it stops working as soon as I paste the code on a different file. I've tried importing the classes on the primary file, but I could make it work (I've tried different import codes because I've found different answers to this question on Google but no one worked, that's why I'm asking here). I believe it's probably because I'm doing something wrong at importing, but I just can't find the error.
Although your code works, keeping js files at the top of the HTML will delay the load time of the page. In a simple scenario like a homework, there's no need to worry, but in large projects it becomes crucial.
And by reading your code, it just starts when all page has already loaded, so no need to put it in the head.
Have you tried doing this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="first.js"></script>
<script src="second.js"></script>
<p>Hello World!</p>
</body>
</html>
First, I'll share some code. This is my HTML head:
<head>
<meta charset="utf-8">
<title>Obligatorio1</title>
<link rel="stylesheet" href="css/estilos.css">
<script src="js/funciones.js"></script>
<script src="js/clases.js"></script>
</head>
This is my relevant code on the first JS:
window.addEventListener('load',inicio)
function inicio(){
document.getElementById("botonAgregarPersonas").addEventListener("click",registroPersonas);
}
let personas=[];
function registroPersonas(){
let nombre=document.getElementById("nombrePersonas").value.trim();
let seccion=document.getElementById("seccionPersonas").value;
let mail=document.getElementById("emailPersonas").value.trim();
let esta=false;
for (i=0;i<personas.length&&!esta;i++){
if (nombre==personas[i].nombre) {
esta=true;
}
}
if (esta){
alert("Nombre ya ingresado");
}else {
let Per = new Persona (nombre, seccion, mail);
personas.push(Per);
let texto=Per.nombre+" - Sección: "+Per.seccion+" - "+Per.mail;
agregarElementoEnLista(texto);
agregarEnComboCompras(Per.nombre);
agregarCheckboxes(Per.nombre);
}
}
function agregarElementoEnLista (texto){
let nodoLi=document.createElement("LI");
let nodoTexto=document.createTextNode(texto);
nodoLi.appendChild(nodoTexto);
document.getElementById("lista").appendChild(nodoLi);
And this is the code of my second JS file (the one with the class):
class Persona{
constructor(nombre, seccion, mail){
this.nombre=nombre;
this.seccion=seccion;
this.mail=mail;
}
}
I'll start saying that, while I've found out the issue, I don't understand why does it happen.
Ok, as you can see on the last piece of code, the parameters have the same name as the class attributes. If I would try copying the code on the first JS file, it would work without any issue, but as soon as I work with that code on a separate JS file it would stop working. After touching every part of the code, I ended up changing the parameters name so it would be different than the class attributes, it looks like this now:
class Persona{
constructor(_nombre, _seccion, _mail){
this.nombre=_nombre;
this.seccion=_seccion;
this.mail=_mail;
}
}
And that code right there works totally fine, without changing anything on the rest of the files (neither the first JS file nor the HTML one).
If anyone understands more than me on why does this happens, feel free to edit this answer.
Thanks everyone for the help!

how can i link my javascript file with html???? I think i have linked properly but not working?

WHAT is problem in linking javascript code to html code???
my html code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PARUL</title>
<script src="script.js"></script>
<script>
console.log(x)
</script>
</head>
<body></body>
</html>
my javascript code:
var x="hello world";
You have already linked your HTML code with your JS file.
Follow these steps :
Right click on your mouse and you will get the option Inspect at the bottom.
Click on it and you will get the developer tool having multiple tabs in it like Elements,Console,etc.
You just need to click on the Console tab. Then you will able to see the output which you have given the statement console.log("")

Creating Batch Scripts with JavaScript

I'm trying to make a simple page with JS which generates Batch Scrips based on user input.
This is the prototype code and works fine with Chrome, but clicking on link with Firefox downloads the file as .txt (e.g.: file.bat.txt) and IE is completey unresponsive to the link
Where am i going wrong?
Any issues with "data:text/plain;base64,"?
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
</head>
<body>
click here
<script>
var bat_source = "#echo off\necho Hello world\npause";
document.querySelector("a").href = 'data:text/plain;base64,' + btoa(bat_source);
</script>
</body>
</html>

Browser ignores Javascript [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 7 years ago.
Rookie alert!
Would you tell me why my Javascript code doesn't update the message. The browser runs HTML but ignores the Javascript code. What am I doing wrong?
<!DOCTYPE html>
<html>
<head>
<title>Basic Function </title>
<script type="text/javascript">
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
updateMessage();
</script>
</head>
<body>
<h1> Travel Worthy </h1>
<div id="message">Welcome to our site! </div>
</body>
</html>
You're running the Javascript before you've loaded the body, the message element doesn't exist yet. Either move the script to the end of the <body>, or change the last line to:
window.onload = updateMessage;
so that the function will be loaded after the HTML is loaded.
If the <script> tag is in the <head> element, it gets executed before the HTML elements in the <body> are created. You can put your script tag inside the <body> element, at the end of it, to solve the issue.
Assuming you don't simply have javascript disabled, you could add a window.onload=function(){ surrounding your code.
window.onload=function(){
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
updateMessage();
}
The reason for doing this is because your javascript code is inside your <head>. Thus, the javascript is loaded before the body. When the browser attempts to execute the javascript code, the message element isn't loaded yet and doesn't exist. By adding window.onload=function(){ to surround your code, your entire code will wait until the body is loaded before executing.
When you call your javascript code, the 'message' element isn't already there. I would suggest one of the following two things:
+Put your javascript code at the end of the body ( note that it only need to be after 'message', but putting it at the end is generally the best option )
+Replace your call with window.onload = updateMessage, which will wait until all the page is loaded to execute your javascript
There are already lots of duplicate answers here but there is another way, especially if you want to keep your Javascript code in a script tag in the head. And that is, wrap your Javascript function call in setTimeout -- this causes the function to be executed after the DOM has been parsed, but before the entire window has been loaded.
It's a neat little trick that can be used when you don't have a framework's (such as jQuery) document/ready functionality. window.onload or putting the script at the bottom might cause significant delays if there is lots of heavyweight content (large images?) in the page.
<!DOCTYPE html>
<html>
<head>
<title>Basic Function </title>
<script type="text/javascript">
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
setTimeout(updateMessage);
</script>
</head>
<body>
<h1> Travel Worthy </h1>
<div id="message">Welcome to our site!</div>
<img src="http://cdn.spacetelescope.org/archives/images/publicationjpg/heic1502a.jpg" />
</body>
</html>
Notice I have added a very large image to the page, but the updated message displays before the image fully loads.
If however instead of setTimeout(updateMessage); you use window.onload = updateMessage; as suggested in the currently accepted answer, your message will not get updated until the entire image loads (if you try this out, make sure you do a hard refresh after the first time so you are not getting it from your cache). Same goes for moving the script too far down the page (below the very large image for instance) as below. I honestly think, if you don't have a framework's document/ready functionality, using setTimeout in a script block in the head is the best solution.
MESSAGE NOT UPDATED UNTIL AFTER IMAGE LOADS:
<!DOCTYPE html>
<html>
<head>
<title>Basic Function </title>
</head>
<body>
<h1> Travel Worthy </h1>
<div id="message">Welcome to our site!</div>
<img src="http://cdn.spacetelescope.org/archives/images/publicationjpg/heic1502a.jpg" />
</body>
<script type="text/javascript">
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
updateMessage();
</script>
</html>
You are trying to make the changes before the DOM is loaded. See the code below,
<!DOCTYPE html>
<html>
<head>
<title>Basic Function </title>
</head>
<body>
<h1> Travel Worthy </h1>
<div id="message">Welcome to our site! </div>
</body>
<script type="text/javascript">
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
updateMessage();
</script>
</html>

How to display variables from external JavaScript in HTML. Internet Explorer 7

I realize this is a horribly newbie question, but Ive been trying to fix it for days trying different methods so I just wanted to ask what would you do.
I am attempting to create a web program to use at work, and I have this setup:
Windows 7
IE 7 - Cannot Upgrade.
The "website" is not a webhost, basicly I have a folder on my desktop with html/css/js files and I use IE to run the scripts, no host.
I want to keep a set of vars, mostly strings, in an external JS file and pull the JS into different HTML pages. I want it to write on load of the document.. not on ready. It does not have to be user dynamtic.
Also, When I make the js file, does it have to have a header.. like HTML has doctypes?
I really appreciate your help as I am trying to learn and will cont on my own from here. My setup is much different than most, and im not sure which part was causing my problem so I finally broke down and posted.
When you write your JavaScript file it doesn't have to have any header or doctype. For example you can have a variables.js file that looks just like this:
var x = "abc";
var y = "def";
and have many HTML files that include variables.js like this:
<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>title</title>
</head>
<body>
<!-- page content -->
<script src="variables.js"></script>
<script>
alert(x);
</script>
</body>
</html>
and your variables should be available there. Any script that is included after the reference to your variables.js should have access to everything that was included before without the need to listen to any events.
If you need to listen to the events then I suggest to use jQuery or some other JavaScript framework. An example for jQuery would be:
$(window).load(function() {
alert(x);
});
A more advanced example of changing the DOM elements:
<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>title</title>
</head>
<body>
<p>Select variable:</p>
<p>
Show x
Show y
</p>
<p>Value:</p>
<p id="value"></p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="variables.js"></script>
<script>
$('#show-x').click(function (e) {
e.preventDefault();
$('#value').html(x);
});
$('#show-y').click(function (e) {
e.preventDefault();
$('#value').html(y);
});
</script>
</body>
</html>
If it's not a global variable, you can't display/print/access or whatever you call it because it has a local scope, defined in a function.
You can probably only use a debugger simply to debug it

Categories

Resources