Navigating with Parent and Sibling Selectors
Select the parent of an element and its sibling using `parentNode` and `nextSibling`.
// Select an element with a specific id
var childElement = document.getElementById('myElement');
// Access the parent of the selected element
var parentElement = childElement.parentNode;
// Log the tagName of the parent element to the console
console.log(parentElement.tagName);
This code snippet selects an element with the id 'myElement' and stores it in a variable 'childElement'. It then accesses its parent node using the 'parentNode' property. Finally, it logs the tagName of the parent element to the console.
// Select an element using a query selector, e.g., class
var childElement = document.querySelector('.my-element-class');
// Access the next sibling of the selected element
var siblingElement = childElement.nextSibling;
// Check if the sibling is an element node
if (siblingElement.nodeType === Node.ELEMENT_NODE) {
// Log the tagName of the sibling element to the console
console.log(siblingElement.tagName);
}
This code snippet selects an element using the querySelector method and class '.my-element-class'. It accesses its next sibling node using the 'nextSibling' property. Before logging the tagName, it checks if the sibling is of type ELEMENT_NODE to avoid text or comment nodes.