Reputation: 11
I have following code to check the object whether exists for item listing.
For testing purpose, i only have one object sub_total_0
, however the script keep looping because typeof
cannot determine sub_total_1
is undefined or not exists, and keep going 2,3,4,5,...
var i = 0;
while (typeof document.getElementById("sub_total_" + i) != "undefined") {
var obj_sub_total = document.getElementById("sub_total_" + i);
if (obj_sub_total != "undefined") {
if (fr.order_method_id.value == 1) {
obj_sub_total.style.visibility = "visible";
} else {
obj_sub_total.style.visibility = "hidden";
}
}
i++;
}
Upvotes: 1
Views: 4908
Reputation: 388316
getElementById() return null if element is not found, and the type of null
is object that is why your condition is not working.
You can just check whether it is a truthy value and since the while() loop validates the object there is no need for the if
condition
var i = 0,
obj_sub_total;
while (obj_sub_total = document.getElementById("sub_total_" + i)) {
console.log(obj_sub_total)
if (fr.order_method_id.value == 1) {
obj_sub_total.style.visibility = "visble";
} else {
obj_sub_total.style.visibility = "hidden";
}
i++;
}
Demo: Fiddle
Upvotes: 1
Reputation: 1074118
Your check doesn't work because using typeof
on getElementById
's return value will always give you "object"
, because it returns null
if it can't find it, and typeof null
is "object"
.
Just check the return value directly: If there's an element, it's a "truthy" value (one that coerces to true
when used as a condition); if there isn't one, null
is a "falsey" value (coerces to false
).
So:
while (document.getElementById("sub_total_" + i)) {
You also don't need to look it up twice, which is what you're currently doing; instead:
var obj_sub_total;
while ((obj_sub_total = document.getElementById("sub_total_" + i)) != null) {
(You don't technically need the != null
there, but without it it looks a bit like you've accidentally used =
where you wanted ==
.)
Another alternative would be to use a class and querySelectorAll
:
var list = document.querySelectorAll(".sub_total");
Then loop while i
is < list.length
, e.g.:
var list = document.querySelectorAll(".sub_total");
for (i = 0; i < list.length; ++i) {
var obj_sub_total = list[i];
// ...
}
Or you could do that even when using id
s:
var list = document.querySelectorAll("[id^=sub_total]");
Upvotes: 1
Reputation: 943185
You have
typeof document.getElementById("sub_total_" + i) != "undefined"
and
if (obj_sub_total != "undefined") {
getElementById
returns either null
or an HTML element. Neither of these are the string "undefined"
and the type of each of this will be "object"
. Thus your conditions don't make sense.
You test for truthfulness instead. An HTML element will always be true and null
will always be false.
while (document.getElementById("sub_total_" + i)) {
and
if (obj_sub_total) {
Upvotes: 1