I have 2 HTML files: A.html and B.html. The purpose is to count the number of specific DIVs in A.html and display this number once B.html is opened.
A.html contains:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" media="all" />
<script type="text/javascript" src="style/js/scripts.js"></script>
</head>
<body>
<div class="elem1"></div>
<div class="elem2"></div>
<div class="elem2"></div>
<div class="elem2"></div>
<div class="elem1"></div>
<div class="elem2"></div>
</body>
</html>
B.html contains:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" media="all" />
<script type="text/javascript" src="style/js/scripts.js"></script>
</head>
<body onload="CntrElem2()">
The number of elem2 in A.html is: <span id="myNum"></span>.
</body>
</html>
The javascript (in style/js/scripts.js) function is:
function CntrElem2() {
var NumOfElem2 = document.querySelectorAll(".elem2");
document.getElementById("myNum").innerHTML = NumOfElem2.length;
}
So, the idea is - when I open B.html, it calls for the CntrElem2 function from scripts.js, which in turn should go and count the number of class="elem2" in A.html (in my case = 4) and display it. What I obviously get is = 0 (since CntrElem2 counts for elem2 in the HTML file it was called from, i.e. B.html and not A.html). How can I specify which HTML file I want querySelectorAll to apply on? Thanks!
Read the A.html document with a fetch, put the html in a div and query the div using querySelectorAll, change your function to the following:
async function CntrElem2() {
let aHtml = await (await fetch('A.html')).text();
let div = document.createElement('div');
div.innerHTML = aHtml;
let numOfElem2 = div.querySelectorAll(".elem2");
document.getElementById("myNum").innerHTML = numOfElem2.length;
}