jhoog
jhoog

Reputation: 45

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

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?

Upvotes: 2

Views: 46

Answers (2)

s.kuznetsov
s.kuznetsov

Reputation: 15223

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>

Upvotes: 1

Unmitigated
Unmitigated

Reputation: 89442

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>

Upvotes: 1

Related Questions