0

I have some links within div. If users click any area in the div, it should do something. But it should do something else if users click on a link.

How could I find out if the click is on a link? BTW, I cannot use onclick() function on the link.

<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
  </head>
  <body>
    <div class="mydiv">
      do something<br />
      <a href="#"> do other</a><br />
      do something<br />
    </div>

    <script>
      $(document).ready(function () {
        $('.mydiv').click(function () {
          var ahref = $(this).attr('href');
          if (ahref == null) {
            alert('do something');
          } else {
            alert('do other');
          }
        });
      });
    </script>
  </body>
</html>

1 Answer 1

1

You can use the nodeName property to check whether the clicked element is having an a tag or not.

<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
  </head>
  <body>
    <div class="mydiv">
      do something<br />
      <a href="#"> do other</a><br />
      do something<br />
    </div>

    <script>
      $(document).ready(function () {
        $('.mydiv').click(function (e) {
          if (e.target.nodeName == 'A') {
            alert('do other');
          } else {
            alert('do something');
          }
        });
      });
    </script>
  </body>
</html>

https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeName

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.