Code Snippets
Pull content from another page
Pull content from another page
404 page need a collection list? Webflow told you it can't happen? We've got you covered. Use this code to pull in the nav or entire page design from another page into your 404.
<script>
/**
* Fetches HTML content from a specified URL and appends a selected element from it to the current document.
* Useful for dynamically loading and displaying content from another part of your website.
*/
async function fetchAndAppendElement() {
try {
// Specify the URL from which to fetch HTML content. Adjust '/' to your specific needs.
const response = await fetch('/');
// Check if the fetch request was successful
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Extract the HTML text from the response
const html = await response.text();
// Create a temporary container to parse the fetched HTML text
const container = document.createElement('div');
container.innerHTML = html;
// Adjust the selector below to target the specific element you want to fetch from the fetched content
const fetchedElement = container.querySelector("[element-ajax='content']");
if (fetchedElement) {
// Adjust the selector below to target where in the current document you want to append the fetched element
const appendItem = document.querySelector("[element-ajax='wrapper']");
// Clone the fetched element to prevent modifying the original element in the temporary container
const clonedElement = fetchedElement.cloneNode(true);
// Append the cloned element. Ensure appendItem is not null before appending.
if (appendItem) {
appendItem.appendChild(clonedElement);
}
} else {
console.error('Failed to fetch the element. Check the selector for the element you are trying to fetch.');
}
} catch (error) {
console.error('An error occurred during the fetch and append operation:', error);
}
}
/**
* Calls fetchAndAppendElement function when the page has finished loading.
* This ensures the DOM is ready for manipulation.
*/
window.addEventListener('DOMContentLoaded', fetchAndAppendElement);
</script>
Similar Code Snippets
Get class name from element
A nice little script that will return the first class applied to an element. It's part of our internal slider code, but has lots of uses when other js libraries are involved.
Move elements at different breakpoints
A useful javascript snippet that lets you move elements to a new location at different breakpoints. Perfect if you can only have 1 instance of an element on the page but it needs to change position.
Calculate sizes in CSS
CSS's calc() function allows you to perform calculations to determine CSS property values. It's incredibly useful for responsive design, such as when you need to adjust sizes dynamically. For example, if you want a div to be 100% of the viewport width minus a certain margin, you can use calc():