Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading