I wanted to set a class on a WordPress block so that any nested link would extend to the entire block. There are many examples of stretching a link to its parent container using CSS, but I had complicated <DIV> with many nested elements.
I could easily apply a hover and class to the block in WordPress. If I could use the class to stretch the link, it would match the boundaries of the hover for the best UI effect.
Here is how I did it.
document.addEventListener('DOMContentLoaded', () => {
// Find all elements with the 'stretch-link' class
document.querySelectorAll('.stretch-link').forEach(element => {
// Add a click event listener to the element
element.addEventListener('click', () => {
// Find the nested 'a' tag within the element
const nestedLink = element.querySelector('a');
if (nestedLink) {
// Redirect to the URL of the nested link
window.location.href = nestedLink.href;
}
});
});
});
This JavaScript will:
- load when the page loads
- search for all elements for the ‘stretch-link’ class
- add a click event handler to elements that then
- search for a nested A tag
- go to the HREF of the tag found
This is the CSS to change the cursor to a pointer when it enters the block
/* Add pointer cursor for elements with the 'stretch-link' class */
.stretch-link {
cursor: pointer;
}
At the time of this writing, this code is in use here.