-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path04-traversing-the-dom.js
89 lines (73 loc) · 1.93 KB
/
04-traversing-the-dom.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* ******************************
* Traversing the DOM
* ******************************
**/
let val;
const list = document.querySelector('ul.collection');
const listItem = document.querySelector('li.collection-item:first-child');
val = listItem; // returns first li item
val = list; // returns ul
/**
* ********************
* Get child nodes
* ********************
**/
val = list.childNodes;
val = list.childNodes[0]; // returns first node object within the list
val = list.childNodes[0].nodeName;
val = list.childNodes[3].nodeType;
/**
* ********************
* Child node type lookup table
*
* 1 = Element
* 2 = Attribute (deprecated)
* 3 = Text node
* 8 = Comment
* 9 = Document itself
* 10 = Doctype
* ********************
**/
/**
* ********************
* Get children element nodes
* ********************
**/
val = list.children;
val = list.children[1];
list.children[1].textContent = 'Hello';
/**
* ********************
* Get children of children element nodes
* ********************
**/
val = list.children[3].children;
val = list.children[3].children[0]; // access specific index of the children of children elements.
list.children[3].children[0].id = 'test-link'; // add 'test-link' id
/**
* ********************
* Other child nodes & children nodes properties
* ********************
**/
// First child
val = list.firstChild;
val = list.firstElementChild;
// Last child
val = list.lastChild;
val = list.lastElementChild;
// Count child elements
val = list.childElementCount;
// Get parent node
val = listItem.parentNode;
val = listItem.parentElement;
val = listItem.parentElement.parentElement;
// Get next sibling
val = listItem.nextSibling;
val = listItem.nextElementSibling;
val = listItem.nextElementSibling.nextElementSibling;
// Get previous sibling
val = listItem.previousSibling;
val = listItem.previousElementSibling;
val = listItem.nextElementSibling.nextElementSibling.previousElementSibling;
console.log(val);