Inherit Link; JavaScript Linked Inheritance

ByChristopher Nathaniel |

Wrapping lots of elements inside of an a tag, which is an inline element isn’t an ideal way of writing HTML. Although from a usable perspective it works, keeping elements completely semantic is essential for screen-readers and search-engines.

Creating a solution to avoid wrapping everything in <a></a> tags is not something new, and Microsoft used to use a solution very similar to keep semantics in their pages.

Essentially, this code will make the .makelink class a link, and it will get its URL from the first a-tag it finds in the DOM below it. This pre-existing script below has a few additional options to help us integrate it better in to our websites – for example if the element contains a class of .disable__link then the script simply will not run – this is useful when managing click states without removing the .makelink class. Secondly, we also identify if we need to open the link in a new window or not, and to do this we simply get the attribute of our <a></a> and look for target=”_blank”. If the condition is met, we open a new window.

It is worth noting that this will not work if managing dynamic data, and is designed to physically open a new page or window, not dynamically load in new information with an AJAX / XMLHTTP request.

See the JavaScript example;

/* JavaScript */
document.querySelectorAll(".makelink").forEach(function (fELink) {
   if(!fELink.classList.contains("disable__link")) { /* Optional if-statement for conditional logic */
      fELink.addEventListener("click", function () {
          let qSLink = fELink.querySelector("a"); /* Find the closest <a></a> */

          (qSLink.getAttribute("target") === "_blank") ? window.open(qSLink.href, "_blank") : window.location.href= qSLink.href; /* Manage target="_blank" */
      });
   }
});

See Basic HTML;


<div class="makelink">
   <a href="">My Link</a>
</div>

See additional HTML examples

<!-- HTML -->
<div class="makelink">
   <h1>Hello World!</h1>
   <h2>This is the second heading.</h2>
   <p>Lorem Ipsum Set dolor</p>

   <img src="./image.webp">

   <ol>
      <li>Feature 1</li>
      <li>Feature 2</li>
      <li>Feature 3</li>
   </ol>

   <a href="./helloworldtwo.html">Read More</a>
</div>

<div class="makelink">
   <h1>Hello World!</h1>
   <a href="./helloworldtwo.html" target="blank">Read More in a New Window</a>
</div>

If everything is successful, you should be able to click on anything in make link, and it will go to the designated link.

create build imagine design code grow enhance innovate inspire prototype debug wireframe integrate optimise performance scalability UI UX
0