JQuery Get value of Child Selector for a .on listener for click event

Viewed 40

I am setting up some JS to grab the id value of a clicked item that was dynamically added within a div using the JQuery .on() event handler. My current code is as follows:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parentDiv">
    <i id="test1">1</i>
    <i id="test2">2</i>
    <i id="test3">3</i>
</div>

<script>
$("#parentDiv").on('click', 'i[id^="test"]', function() {
    var child_id = $(this).id;
    child_id = child_id.replace("test","");
    alert(child_id);
});
</script>

The <i> elements are added dynamically so I can't listen directly for clicks on them. The area that doesn't seem to be functioning correctly is the line: var child_id = $(this).id; It seems to be not working properly entirely or pulling the parents id, but not the child's id. Is there a command to get the child selector that was clicked, rather than the parents data?

2 Answers

Use .prop or directly access id without wrapping the element in a jQuery object (i.e., this.id).

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parentDiv">
    <i id="test1">1</i>
    <i id="test2">2</i>
    <i id="test3">3</i>
</div>

<script>
$("#parentDiv").on('click', 'i[id^="test"]', function() {
    var child_id = $(this).prop('id');
    child_id = child_id.replace("test","");
    console.log($(this).prop('id'), this.id);
    console.log(child_id);
});
</script>

Use attr() method:

var child_id = $(this).attr('id');

$("#parentDiv").on('click', 'i[id^="test"]', function() {
    var child_id = $(this).attr('id');
    child_id = child_id.replace("test","");
    alert(child_id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parentDiv">
    <i id="test1">1</i>
    <i id="test2">2</i>
    <i id="test3">3</i>
</div>

Related