I think you're referring to the closest() method! Here's a version using this built-in DOM method:
function getAllUrls() {
const anchors = document.querySelectorAll('a[href]');
const urls = Array.from(anchors).map(anchor => {
// Try to find the closest ancestor that is or contains an h1 or h2
let nearestHeading = null;
// First check if the anchor itself contains a heading
const headingInside = anchor.querySelector('h1, h2');
if (headingInside) {
nearestHeading = headingInside.textContent.trim();
} else {
// Use closest to find ancestor h1 or h2
const headingAncestor = anchor.closest('h1, h2');
if (headingAncestor) {
nearestHeading = headingAncestor.textContent.trim();
} else {
// Look for the closest ancestor that contains an h1 or h2
let parent = anchor.parentElement;
while (parent) {
const heading = parent.querySelector('h1, h2');
if (heading && !heading.contains(anchor)) {
nearestHeading = heading.textContent.trim();
break;
}
parent = parent.parentElement;
}
}
}
return {
url: anchor.href,
text: anchor.textContent.trim(),
nearestHeading: nearestHeading
};
});
return urls;
}
// Usage
const urlList = getAllUrls();
console.log(urlList);
Note about closest(): This method only searches upward through the element's ancestors. It doesn't search siblings or other branches of the DOM tree. So if your heading structure looks like this:
<div>
<h2>Section Title</h2>
<p>Some text with <a href="#">a link</a></p>
</div>
The closest() method won't find the h2 because it's a sibling of the paragraph, not an ancestor of the anchor.
If you want a more comprehensive search that includes siblings and cousins, here's an enhanced version:
function getAllUrls() {
const anchors = document.querySelectorAll('a[href]');
const urls = Array.from(anchors).map(anchor => {
let nearestHeading = null;
// Strategy 1: Check inside the anchor
const headingInside = anchor.querySelector('h1, h2');
if (headingInside) {
nearestHeading = headingInside.textContent.trim();
}
// Strategy 2: Check if anchor is inside a heading
if (!nearestHeading) {
const headingParent = anchor.closest('h1, h2');
if (headingParent) {
nearestHeading = headingParent.textContent.trim();
}
}
// Strategy 3: Find the nearest common ancestor that contains a heading
if (!nearestHeading) {
let current = anchor.parentElement;
while (current) {
// Check all headings in this container
const headings = current.querySelectorAll('h1, h2');
for (const heading of headings) {
// Make sure the heading comes before our anchor in document order
if (heading.compareDocumentPosition(anchor) & Node.DOCUMENT_POSITION_FOLLOWING) {
nearestHeading = heading.textContent.trim();
break;
}
}
if (nearestHeading) break;
current = current.parentElement;
}
}
return {
url: anchor.href,
text: anchor.textContent.trim(),
nearestHeading: nearestHeading
};
});
return urls;
}