Jordan Baron Jordan Baron - 2 months ago 7
Javascript Question

JavaScript - If statement won't work

I am making an app with Electron. I am having a problem with my if statement, it's not working! I have tried putting an alert to check if the if the if statement was the problem.

var nodeList = history.getElementsByTagName("span").length;

if(nodeList == 6) {
alert("Test");
nodeList.children[0].remove();


Here is my full code



var request = require('request');

setInterval(function() {
request("http://finance.google.com/finance/info?client=ig&q=aapl" , function(error, response, body) {
body = body.slice(3);
body = JSON.parse(body);
console.log(body);

newPrice(body);
});
}, 1000)

var lastPrice;

function newPrice(arr) {
currentPrice = arr[0]["l"];
var history = document.getElementById("priceHistory");

if(lastPrice < currentPrice) {
var newElText = "▲";
var wrap = document.createElement("span");
wrap.className = "up";

} else if(lastPrice > currentPrice) {
var newElText = "▼";
var wrap = document.createElement("span");
wrap.className = "down";
} else if(lastPrice==currentPrice) {
var newElText = "⁃";
var wrap = document.createElement("span");
wrap.className = "noChange";
}
var textNode = document.createTextNode(newElText);
history.appendChild(textNode);

var nodeList = history.getElementsByTagName("span").length;

if(nodeList == 6) {
nodeList.children[0].remove();
}

document.getElementById("price").innerHTML = currentPrice;
lastPrice = currentPrice;
}

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Google Stock</title>

<style>
body {
background: black;
color: white;
font-family: Arial;
text-align: center;
}

.up {
color: green;
}

.down {
color: red;
}

</style>

</head>
<body>
<h3>Current Share Price: GOOG</h3>
<div class="the-price" id="price"></div>

<div class="up-down" id="priceHistory"></div>


<script type="text/javascript">
require("./stock.js")
</script>

</body>
</html>





I am using NodeJS

Answer

If statements don't stop working. They will always check the condition (nodeList == 6) and run the body of the statement if that value is truthy.

So one of 3 things could be happening:

  • The condition is not truthy (nodeList is not == to 6). Check this by logging out the value of nodeList, or changing the statement's condition to true to force that part of the code to run.
  • The if statement is not being run at all (not even checking the condition). Check this by logging just before the if statement in question, to make sure the code that includes the if statement actually gets that far. For example, if there's another if statement around the one that isn't running, and that one's condition is falsey, then anything inside it won't run either (including this problematic if statement).

I don't know if any of that will help, but it's always good to do some debugging so you have something to work with. Let us know what happens with these tests and maybe we can figure out what's going on.