Top Banner
JavaScript Training Goal Trainers Format Lecture Exercises Ask Questions! bitovi/js-trainin
8

Traversing elements in the DOM

Aug 17, 2015

Download

Technology

alexisabril
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Traversing elements in the DOM

JavaScript Training

Goal Trainers Format

• Lecture• Exercises• Ask Questions!• bitovi/js-training

Page 2: Traversing elements in the DOM

Traversing

Page 3: Traversing elements in the DOM

element.childNodeselement.firstChildelement.lastChildelement.nextSiblingelement.previousSiblingelement.parentNodeelement.children

<ul> <li> … </li> <li> Text Node <a href="">Link</a> <span></span> <li> <li> … </li></ul>

from an Element

Page 4: Traversing elements in the DOM

Exercise

Add the next method to $:

$('#doberman').next() //-> $[ div#beagles ]

$('#doberman').next().next() //-> $[ div#boxer ]

$('#doberman').next().next().next() //-> $[]

$('#doberman, #beagles').next() //-> $[ div#beagles, div#boxer ]

hint: Make sure you check for text nodes.

Page 5: Traversing elements in the DOM

Exercise

Add the prev method to $:

$('#doberman').prev() //-> $[ ul#breeds ]

Page 6: Traversing elements in the DOM

Exercise

Add the parent method to $:

$('#breeds').parent() //-> $[ HTMLBodyElement ]

Page 7: Traversing elements in the DOM

Exercise

Add the children method to $:

$('#breeds').children() //-> $[ li, li, li ]

Page 8: Traversing elements in the DOM

Exercise

Add a private helper method makeTraverser to $ and reimplement find,next, prev, parent, children:

children: makeTraverser(function() {return this.children;

});

parent: makeTraverser(function() {return this.parentNode;

});

hint: Look at the similarities of each method and refactor the similar code out into its own method.