olidev
olidev

Reputation: 20684

Click on div using jquery error

I have this HTML:

<div class="divHolder">
   <a href="./"><img src="./images/image6.jpg"/></a>
</div>
<div class="divHolder">
   <a href="./IT.aspx"><img src="./images/image7.jpg"/></a>
</div>

In my JavaScript I have:

$('.divHolder').click(function () {

    var link = $(this).find("a").attr("href");

    if (link != null) {
         location.href = link;
    }
});

However, every time I click on a div, the href of the div is always the last one: for example in this case is: IT.aspx.

What did I do wrong?

Upvotes: 0

Views: 86

Answers (1)

Matthew Nessworthy
Matthew Nessworthy

Reputation: 1428

A better way to do this would be the following

$('.divHolder:has(a)').click(function () {
  location.href = $(this).find("a").attr("href");
});

Upvotes: 1

Related Questions