1

I am using this script to find an a href within a parent element and then go to that link if the parent div is clicked.

jQuery(".card").click(function() {
  window.location = jQuery(this).find("a").attr("href"); 
  return false;
});

However, I am finding that if there is no a href at all, it is still adding a link to 'undefined' (resulting in 404).

I am fairly certain I need an if to detect if there is an a href, but cannot get it to work:

jQuery(".card").click(function() {
     if (jQuery(this).find("a").attr("href").length {
  window.location = jQuery(this).find("a").attr("href"); 
  return false;
  }
});
Sly
  • 39
  • 6
  • I don't know what are all your requirements, but I would assume that by just calling a click on the hyperlink you would achieve the same result, with the bonus of not doing anything if the hyperlink isn't available. – emerson.marini Dec 07 '20 at 16:46
  • Missing a closing parenthesis after `length` – chiliNUT Dec 07 '20 at 16:47
  • looks like he wants the entire div to behave like the anchor's link – ComplexityAverse Dec 07 '20 at 16:49
  • 1
    Does this answer your question? [How to trigger a click on a link using jQuery](https://stackoverflow.com/questions/5811122/how-to-trigger-a-click-on-a-link-using-jquery) – emerson.marini Dec 07 '20 at 16:53

1 Answers1

1

You will want to check to see if the a exists via length.

jQuery(".card a",function(){
    $(this).parent().addClass("has-link");
})

jQuery(".card.has-link").click(function() {
  window.location = jQuery(this).find("a").attr("href"); 
  return false;
});
imvain2
  • 15,480
  • 1
  • 16
  • 21