3

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;
}
1
  • 4
    You do realize that while is a loop, right? It will execute over and over until the condition becomes false. Commented Feb 24, 2012 at 4:34

2 Answers 2

9

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).

Sign up to request clarification or add additional context in comments.

Comments

0

Because he is walking up..

If you see pretty well, in the loop he is assigning the target again with its parent and the parent is not nodetype 1

 target = target.parentNode;

I don't know what is he trying or what is the purpose or the goal but it's quite simple..

Imagine the DOM

<div>
  <div>
     <div>
        <div>
           Imagine he starts from here.. he will always get the max parent with not nodetype 1 the hightes parent so the first div..
         </div>
     </div>
  </div>
</div>

SO basically. He is getting the Higher parent ... That's why is he looping.. if uses the If.. he will get just the First parent

3 Comments

But nodeType==1 is an element node, so as soon as you walk out of the TextNode (in the unlikely case that it fired the event) you have an element.
It keeps walking as long as nodeType!=1, which means that it stops as soon as nodeType==1, which it will always do either immediately or after one iteration.
Yes my mystake, you are right, BUT i think he did it for something look at this example javascriptkit.com/domref/nodetype.shtml

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.