write javascript to get a list of all urls on a website in a array with the following…
- User
write javascript to get a list of all urls on a website in a array with the following attributes:
url text inside the a tag text of the nearest h1 or h2 tag in the node chain
Assistant
Certainly! Below is a JavaScript code snippet that will gather all URLs on a webpage into an array. Each element in the array will have the following attributes:
url: The URL from thehrefattribute of theatag.text: The text inside theatag.headingText: The text of the nearesth1orh2tag in the node chain.
document.addEventListener("DOMContentLoaded", function() { const links = document.querySelectorAll('a'); const result = []; links.forEach(link => { if (link.href) { const urlObject = { url: link.href, text: link.textContent.trim(), headingText: getNearestHeadingText(link) }; result.push(urlObject); } }); console.log(result); }); function getNearestHeadingText(element) { let currentNode = element; while (currentNode) { if (currentNode.tagName === 'H1' || currentNode.tagName === 'H2') { return currentNode.textContent.trim(); } currentNode = currentNode.parentNode; } return null; }Explanation:
- Event Listener: The script waits for the DOM to be fully loaded using
DOMContentLoaded. - Query Selector: It selects all
atags on the page usingdocument.querySelectorAll('a'). - Iteration: It iterates over each
atag. - URL Object: For each
atag, it creates an object with the required attributes:url: Thehrefattribute of theatag.text: The text content inside theatag, trimmed of any extra whitespace.headingText: The text of the nearesth1orh2tag found by traversing up the node chain.
- Helper Function:
getNearestHeadingTexttraverses up the DOM tree from the given element to find the nearesth1orh2tag and returns its text content. If no such tag is found, it returnsnull.
Usage:
- You can run this script in the browser’s console or include it in your webpage to log the array of URL objects to the console.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.