Thumbnail of JavaScript

Make a Clickable Link with JavaScript Instead of an HTML Anchor

Sometimes you just can’t edit the HTML but still need to make a div clickable. Here’s how to do it with JavaScript. No jQuery needed.

<script>
document.addEventListener("DOMContentLoaded", function () {
  document.querySelectorAll(".YOUR-CLASS-NAME").forEach(function (box) {
    // Skip boxes that already contain a link or form control (no nested links)
    if (box.querySelector("a, button, input, select, textarea")) return;
    var link = document.createElement("a");
    link.href = "YOUR-URL-LINK";
    while (box.firstChild) link.appendChild(box.firstChild);
    box.appendChild(link);
  });
});
</script>

Replace .YOUR-CLASS-NAME with your div’s class and "YOUR-URL-LINK" with your destination link. The script waits until the page has loaded, then moves the div’s content into a real link, so it also works with the keyboard, middle-click and “open in new tab”. Boxes that already contain a link or a form field are skipped, because links can’t be nested.

Using jQuery in WordPress

WordPress loads jQuery in “no-conflict” mode, so the $ shortcut isn’t available by default. If you prefer jQuery, use jQuery(function ($) { … }), which runs when the page is ready and lets you use $ inside:

<script>
jQuery(function ($) {
  $(".YOUR-CLASS-NAME").each(function () {
    // Skip boxes that already contain a link or form control (no nested links)
    if ($(this).find("a, button, input, select, textarea").length) return;
    $(this).contents().wrapAll('<a href="YOUR-URL-LINK"></a>');
  });
});
</script>

Pretty simple, huh? Of course, if you can edit the HTML, wrapping the content in an <a> tag yourself is still the best option.

Leave a Comment

Your email address will not be published. Required fields are marked *