0

I have a simple html snippet.

<div class="group">
    <div class="A1_B1 symptom">
        <ul><li><a href="#" class="hit">Click Symptom</li></ul>
    </div>
    <div class="A2_B2 remedy">
        <ul><li><a href="#" class="hit">Click Remedy</li></ul>
    </div>
</div>

Now for the click action...

$(document).on("click", ".hit", function (ev) {
if($(this).parents(".symptom"))
    alert("Symptom Clicked");
if($(this).parents(".remedy"))
    alert("Remedy Clicked");
});

$(this) is supposed to refer only the element that I have clicked. Why does it alert both the alert statements even if the if conditions do not satisfy?

Jay
  • 744
  • 4
  • 14
  • 30
  • 1
    `parents` returns an object and objects are truthy values in JavaScript. Use `parents(...).length` instead. – Ram May 27 '21 at 17:58

1 Answers1

1

Change your code as following

$(document).on("click", ".hit", function (ev) {
if($(this).parents(".symptom").length>0)
    alert("Symptom Clicked");
if($(this).parents(".remedy").length>0)
    alert("Remedy Clicked");
});

https://jsfiddle.net/1mz8s73b/

Chamika Sandamal
  • 23,565
  • 5
  • 63
  • 86