William
William

Reputation: 4578

Are global variables required for some types of DOM manipulation with javascript?

In the example code below, I want to know why the variable called child must be global ( no var) in order for the code to work. I also want to know if the code below is considered bad practice due to having a global variable and how a better practiced rendition of the code below might look. Thanks.

<!DOCTYPE html>
<meta charset="UTF-8">
<title>dom</title>

<div class="product">
<h2> Product Name </h2>
<img src="pic.jpg" />
<p> Description </p> </div>

<script>
var products = document.getElementsByClassName("product"), 

        child;   // how come var breaks the code ?

    for ( i = 0; i < products.length; i++) {
        child = products[i].firstChild;
        while (child.nodeType !== 1) {
            child = child.nextSibling;
        }
        console.log(child);
    }
</script>

Upvotes: 0

Views: 51

Answers (1)

JohnB
JohnB

Reputation: 13713

You already have a var, as there is a comma before child. Hence adding var would give you

var product, var child

which is illegal.

child is not global, because the var in

var product, child

applies to the whole list of variables following var. (Well, child is global anyway since it is not nested in a function. But that does not have to do with var or not var.)

If you insist on having var twice, write

var product = ... ;
var child;

Upvotes: 1

Related Questions