Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If vs. while in specific JavaScript code

Tags:

javascript

Why does the author of Test-Driven JavaScript Development (Christian Johansen) use the while statement instead of the if statement in the code below?

function getEventTarget(event) {
    var target = event.target || event.srcElement;

    while (target && target.nodeType != 1) {
        target = target.parentNode;
    }

    return target;
}
like image 578
Dathan Avatar asked Aug 14 '26 18:08

Dathan


1 Answers

Because the author wanted to keep walking up the tree until the correct node type was found; it might not be the immediate parent.

However, in this case it makes no sense, as parentNode will always return an element in real-world usage (or a Document).

like image 136
Phrogz Avatar answered Aug 16 '26 11:08

Phrogz