Traversal is selecting an element based on its relationship to another element within the DOM.
Remove Element – Exploring Parents
Steps of removing an element:
- Select child
- Traverse to parent
- Remove child from parent
Like getting a reference to an element’s parent node, using the parentNode
property.
let paragraph = document.getElementById('myParagraph');
let parent = paragraph.parentNode;
Remove element example
//...
let li = event.target;
let ul = li.parentNode;
ul.removeChild(li);
//...
It is possible to chain the parentNode property to traverse up the DOM
let ancestor = p.parentNode.parentNode.parentNode
Move Element – Exploring Siblings
<ul>
<li>grapes </li>
<li>lavender </li>
<li>plums </li>
</ul>
Steps of moving an element:
- Select element
- Select previous element sibling
- Select parent
- Insert element into parent before previous sibling
Select Sibling
Trying to select plums
previous sibling using the .previousSibling property is not recommended.
>> let li = listUl.querySelectorAll('li')[2];
>> li
<li>plums</li>
>> li.previousSibling
#text
>> li.previousSibling.textContent
"
"
>> li.previousSibling.previousSibling
<li>lavender</li>
.previousSibling
is NOT preferred, because it selects the previous node in the DOM, which may not be necessarily an HTML element (e.g. a new line text used to organize the code). Unlike previousSibling, previousElementSibling always returns a DOM element.
Always use .previousElementSibling
.
Insert Element
Using .insertBefore()
method.
parentNode.insertBefore( newNode, refNode );
Inserting Before
if (event.target.className == 'up') {
let li = event.target.parentNode;
let nextLi = li.previousElementSibling;
let ul = li.parentNode;
if (prevLi) {
ul.insertBefore(li, prevLi);
}
}
if (prevLi) {...}
Prevents the first child from being moved to the bottom of the list.
Inserting After
There is no insertAfter method in JavaScript. So we must use .nextElementSibling
and then insertBefore()
but with its arguments exchanged.
if (event.target.className == 'down') {
let li = event.target.parentNode;
let nextLi = li.nextElementSibling;
let ul = li.parentNode;
if (prevLi) {
ul.insertBefore(nextLi, li);
}
}
Children
Get all children elements of a node, with the children
property.
const lis = listUl.children;
for (let i = 0; i < lis.length; i += 1){
attachListItemButtons(lis[i]);
}
Given a selected ul element, the following two lines of code are functionally equivalent:
ul.removeElement(ul.children[0]);
and
ul.removeElement(ul.firstElementChild);
elementParent.children
Selects all HTML children of parent element.
elementParent.firstElementChild
Selects first child of parent element.
elementParent.lastElementChild
Selects last child of parent element.