I want to have a dynamic page that displays whether a certain player is a real player or a computer based on url parameters. The parameters themselves work fine and the data is collected correctly, but the DIV tags I have aren’t updating their text.
The issue is to do with declaring the variables p1 to p6, which are being shown as null in the console. I’m unsure on why this is since I’m even calling the whole thing inside the onload function. The console.log calls at the end of each case are also working fine.
Code Snippet
window.onload = function() {
var p1 = document.getElementById("p1"),
p2 = document.getElementById("p2"),
p3 = document.getElementById("p3"),
p4 = document.getElementById("p4"),
p5 = document.getElementById("p5"),
p6 = document.getElementById("p6");
var url = window.location.href,
params = url.split('?')[1].split('&'),
data = {},
tmp;
for (var i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
switch (data.players) {
case 1:
p2.innerHTML = "Computer";
p3.innerHTML = "Computer";
p4.innerHTML = "Computer";
p5.innerHTML = "Computer";
p6.innerHTML = "Computer";
console.log(data.players)
break;
case 2:
p3.innerHTML = "Computer";
p4.innerHTML = "Computer";
p5.innerHTML = "Computer";
p6.innerHTML = "Computer";
console.log(data.players)
break;
case 3:
p4.innerHTML = "Computer";
p5.innerHTML = "Computer";
p6.innerHTML = "Computer";
console.log(data.players)
break;
case 4:
p5.innerHTML = "Computer";
p6.innerHTML = "Computer";
console.log(data.players)
break;
case 5:
p6.innerHTML = "Computer";
console.log(data.players)
break;
default:
console.log(data.players)
break;
}
}
<div class="wrapper">
<div></div>
<div id="p1">p1</div>
<div id="p2">p2</div>
<div></div>
<div id="p3">p3</div>
<div></div>
<div></div>
<div id="p4">p4</div>
<div></div>
<div id="p5">p5</div>
<div id="p6">p6</div>
<div></div>
</div>
2
Answers
Your main issue is that a query param is of type String, but you’re using
case 1:
instead ofcase "1":
. Besides that I would not useswitch case
at all.Instead of using IDs, use classes like
All the JavaScript you need is:
.player
DIVs.get()
method to retrieve the String of the number of human players from the URI query search param.slice(-N)
to get the last N DIV elementstextContent
I cleaned up your code while keeping my answer understandable.
First, you will want to use DOMContentLoaded instead of window.onload as DOMContentLoaded will be triggered after the HTML is loaded/parsed.
Next, getting rid of ids is the best long term option. They can be difficult to work with and have more restrictions.
I’m using URL searchParams to parse the query string instead of splitting it.
Using Number I convert the string to a number that is returned from the query string.
I have some double checking functionality to verify that the variable passed is in the proper range.
Then I simply loop through the the starting player number and go to the end of the length of the player divs.