.closest() Element.closest()方法用來獲取:匹配特定選擇器且離當前元素最近的祖先元素(也可以是當前元素本身)。如果匹配不到,則返回null。 var elem = document.querySelector('#some-element'); var closestParent = elem.closest('.pick-me');
appendChild() appendChild()將元素添加到一組元素的結尾 // Create a new element var newNode = document.createElement('div'); // Get the parent node var parentNode = document.querySelector('#some-element'); // Insert the new node after the last element in the parent node parentNode.appendChild(newNode);
使用insertBefore(),並將元素加入至父層的第一個元素之前 // Create a new element var newNode = document.createElement('div'); // Get the parent node var parentNode = document.querySelector('#some-element'); // Insert the new node before the reference node parentNode.insertBefore(newNode, parentNode.firstChild);
使用insertBefore(),並在node後呼叫下一個節點元素 // Create a new element var newNode = document.createElement('div'); // Get the reference node var referenceNode = document.querySelector('#some-element'); // Insert the new node before the reference node referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);