Get de href from each element inside a div and use it

I got following html:

<div class="tmb">
    <p>First element</p>
    <a href="location-one.html">Click me</a>
</div>
<div class="tmb">
    <p>Second element</p>
    <a href="location-two.html">Click me</a>
</div>
<div class="tmb">
    <p>Third element</p>
    <a href="location-three.html">Click me</a>
</div>

What I want to do is to make the whole .tmb-div clickable with the url from it’s a-element child. What I tried so far is:

(function($) {
  $(".tmb:first-child").attr("onclick", "location.href='location-one.html'");
})(jQuery);

This works if I repeat it for every .tmb-div and change the nth-child number and the url. But eventually there will dynamically created more .tmb-div’s in the future. So is there a way to do it automatically?

>Solution :

I hope this would help.

$(function() {
  $(".tmb").each(function() {
    let url = $(this).find("a").attr("href");
    $(this).on("click", function() {
      window.location.href = url;
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tmb">
  <p>First element</p>
  <a href="location-one.html">Click me</a>
</div>
<div class="tmb">
  <p>Second element</p>
  <a href="location-two.html">Click me</a>
</div>
<div class="tmb">
  <p>Third element</p>
  <a href="location-three.html">Click me</a>
</div>

Leave a Reply