jQuery's children()
returns all children of the selector. In your context, you'll get all of the links instead of the one that was clicked. Here's a demonstration:
$(document).on("click", ".alphabet", function() {
let $children = $(this).children();
$children.each((k, item) => console.log(item.id));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="alphabet">
<a id="a">a</a>
<a id="b">b</a>
<a id="c">c</a>
<a id="d">d</a>
</div>
One idea is to target the <a>
tags instead of the <div>
:
$(document).on("click", ".alphabet a", function() {
console.log(this.id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="alphabet">
<a id="a">a</a>
<a id="b">b</a>
<a id="c">c</a>
<a id="d">d</a>
</div>
Another idea is to use the event target:
$(document).on("click", ".alphabet", function(e) {
console.log(e.target.id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="alphabet">
<a id="a">a</a>
<a id="b">b</a>
<a id="c">c</a>
<a id="d">d</a>
</div>
Finally, unless the .alphabet
element or its children are dynamically generated, event delegation is likely not necessary. You can bind the event handler directly to the link elements, like so:
$('.alphabet a').on("click", function(e) {
console.log(this.id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="alphabet">
<a id="a">a</a>
<a id="b">b</a>
<a id="c">c</a>
<a id="d">d</a>
</div>
Also see Event binding on dynamically created elements?